1. Array#reject 方法遍歷一個(gè)集合的每個(gè)元素,并把符合條件的元素刪去。
例如去掉數(shù)組中的所有素?cái)?shù)
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. 判斷是否在命令行運(yùn)行腳本
if $0 == __FILE__
check_usage
compare_inventory_files(ARGV[0], ARGV[1])
end
類似于Java類的main方法,在被其他類導(dǎo)入時(shí)不會(huì)運(yùn)行其中的代碼。
4. Enumerable#any? 方法查找一個(gè)集合中是否有滿足條件的元素
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. 關(guān)于測(cè)試
這本書(Everyday Scripting with Ruby)的很多程序都是依循測(cè)試驅(qū)動(dòng)開(kāi)發(fā)的思想寫出來(lái)的,測(cè)試單元中的方法通常有兩種目的。
一種是direct test,需要測(cè)試那個(gè)函數(shù)就直接調(diào)用那個(gè)函數(shù),傳遞的參數(shù)都是直接寫出來(lái)的。
另一種是bootstrapping test,被測(cè)試函數(shù)的參數(shù)也是通過(guò)生成這些參數(shù)的函數(shù)生成的,即一個(gè)方法測(cè)試了多個(gè)對(duì)象。
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"