有人想出了一個表現Scala特性的列表,裏面用了十個精簡的代碼。馬上,CoffeeScript版本就冒出來了,然後俺想,尼瑪俺要發佈Ruby版本的啊。再說了,俺還發現Ruby的語句比Scala的還乾淨些的說,而且要表達的東西是差不多滴。
1、列表中的每項乘以2
p (1..10).map {|n| n*2}
2、對列表中的數字求和
p (1..1000).inject { |sum, n| sum + n }
或者用Ruby1.8.7版本內建的 Symbol#to_proc語句(1..1000).inject(&:+)
或者還可以直接傳symbol
(1..1000).inject(:+)
3、在字符串裏邊找關鍵字words = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."
words.any? { |word| tweet.include?(word) }
4、讀文件
file_text = File.read("data.txt")
file_lines = File.readlines("data.txt")