Learn Ruby The Hard Way
前言:
學ROR已經有一段時間了,不過還真沒有好好的學過一遍Ruby。
過年期間稍微看過一遍Learn to Program,不過真的是稍微瀏覽,
沒有實際動手去弄,這次一定要每天做一點點啊...不能再廢了!
以下就記錄一下每天的心得。
1. 如何知道require lib的路徑:
在command line中輸入 ruby -e 'puts $:'
2. exercise13中,STDIN.gets 與一般gets的不同
在Learn Ruby The Hard Way中如此解釋:
Important: Also notice that we're using STDIN.gets instead of plain 'ol gets. That is because if there is stuff in ARGV, the default gets method tries to treat the first one as a file and read from that. To read from the user's input (i.e., stdin) in such a situation, you have to use it STDIN.gets explicitly.
簡單來說,gets是kernal#gets(待解),會先去讀取ARGV參數給予的檔案,如果沒有給予,則會轉回standard input(即STDIN),故在這一個練習中必須使用STDIN,因為在有ARGV的情況下,gets會先去尋找第一個參數的檔案。
ex.
ex13.rb first second third
則gets會去找是否有first這檔案,沒有的話則會拋出error,範例如下:
first, second, third = ARGV
puts "The script is called #{$0}." # $0 present for the script name. ex. ex13.rb
puts "First variable is #{first}."
puts "Second variable is #{second}."
puts "Third variable is #{third}."
fourth = STDIN.gets.chomp()
# 如果使用gets,則會去抓first的ARGV,查看是否有**檔案**符合(注意:是檔案不是變數)
puts "The forth variable by STDIN.gets is #{fourth}."
3. exercise 16的加分題:
difference between method and funtion:
A method is on an object.
A function is independent of an object.For Java, there are only methods.
For C, there are only functions.
For Ruby, there are only methods.For C++ it would depend on whether or not you're in a class.
4. exercise 20 關於File中的seek函數
在ex20中提到file.seek(offset, IO::SEEK_SET)
第二個餐數有 IO::SEEK_SET
IO::SEEK_CUR
IO::SEEK_END
目的都是用來將指標指向文件中指定的位置,三者代表的意義如下
SEEK_SET
: 指向offset所指定的位置(從0開始)
SEEK_CUR
: 指向當前位置加上offset值後的位置
SEEK_END
: 指向offset所指定位置,從文字最後面開始(offset須用負數)
SET與END應該都不難理解,來看一下CUR
範例:
file = File.open(foo.txt)
file.readline() # 讀完第一行,此時指標會在第二行開頭
file.seek(1, IO::SEEK_CUR) # 指標指向第二個字
file.readline() # 由第二行第二個字印出
5. class中method self的使用
在class中,method如果使用self, 則為class method, 如果沒有, 則為instance method,舉例如下
class Foo
def bar
puts "Here is bar, an instance method."
end
def self.baz
puts "Here is baz, an class method."
end
end
Foo.bar # => undefined method `baz' for #<Foo:0x007fdf5a04bf78> (NoMethodError)
Foo.baz # => "Here is baz, an class method."
Foo.new.bar # => "Here is bar, an instance method."
Foo.new.baz # => undefined method `baz' for #<Foo:0x007fdf5a04bf78> (NoMethodError)