1. Array#reject 方法遍歷一個集合的每個元素,并把符合條件的元素刪去。
例如去掉數組中的所有素數
nums = nums.reject do | num |
prime?(num)
end
puts nums
2. String#chomp 方法
str.chomp(separator=$/) => new_str
Returns a new +String+ with the given record separator removed from
the end of _str_ (if present). If +$/+ has not been changed from
the default Ruby record separator, then +chomp+ also removes
carriage return characters (that is it will remove +\n+, +\r+, and
+\r\n+).
"hello".chomp #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello \n there".chomp #=> "hello \n there"
"hello".chomp("llo") #=> "he"
3. 判斷是否在命令行運行腳本
if $0 == __FILE__
check_usage
compare_inventory_files(ARGV[0], ARGV[1])
end
類似于Java類的main方法,在被其他類導入時不會運行其中的代碼。
4. Enumerable#any? 方法查找一個集合中是否有滿足條件的元素
irb(main):004:0> deposits = [1, 0, 10000]
irb(main):005:0> deposits.any? do | deposit |
irb(main):006:1* deposit > 9999
irb(main):007:1> end
=> true
5. 關于測試
這本書(Everyday Scripting with Ruby)的很多程序都是依循測試驅動開發的思想寫出來的,測試單元中的方法通常有兩種目的。
一種是direct test,需要測試那個函數就直接調用那個函數,傳遞的參數都是直接寫出來的。
另一種是bootstrapping test,被測試函數的參數也是通過生成這些參數的函數生成的,即一個方法測試了多個對象。
Everyone finds their own balance between testing directly and testing indirectly. You will too.
6. Time#strftime 方法
t = Time.now
t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
t.strftime("at %I:%M%p") #=> "at 08:56AM"