10個驚艷的Ruby單行代碼
有人想出了Scala的10個單行代碼例子。然后CoffeeScript版本迅速崛起,于是我想到發(fā)布一個Ruby版本的。我覺得Ruby的語法比Scala清潔點,雖然實質(zhì)上(至少就這些例子來說)是比較相似的。
1.數(shù)組中的每個元素乘以2
- (1..10).map { |n| n * 2 }
2.數(shù)組中的元素求和
- (1..1000).inject { |sum, n| sum + n }
或使用(內(nèi)置的)Symbol#to_proc語法,自Ruby 1.8.7之后可用:
- (1..1000).inject(&:+)
甚至就直接傳遞一個符號:
- (1..1000).inject(:+)
3.驗證在字符串中是否有tokens存在
- 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")
后者包括“\n”在數(shù)組每個元素的末端,它可以通過附加 .map { |str| str.chop }
或者使用替代版本來做修整:
- File.read("data.txt").split(/\n/)
5.生日快樂
- 4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" }
6.過濾數(shù)組中的數(shù)字
- [49, 58, 76, 82, 88, 90].partition { |n| n > 60 }
7.獲取并解析一個XML Web服務(wù)
- require 'open-uri'
- require 'hpricot'
- results = Hpricot(open("http://search.twitter.com/search.atom?&q=scala"))
這個例子需要open-uri或hpricot或等效庫(如果你愿意,你可以使用內(nèi)置的)。沒有太多的代碼,但Scala在這里明顯勝出。
8.在數(shù)組中查找最?。ɑ?**)值
- [14, 35, -7, 46, 98].min
- [14, 35, -7, 46, 98].max
9.并行處理
- require 'parallel'
- Parallel.map(lots_of_data) do |chunk|
- heavy_computation(chunk)
- end
不像Scala,多核支持不是內(nèi)置的。它需要parallel 或類似的東西。
10.埃拉托斯特尼篩法
Scala的單行代碼很聰明,但完全不可讀。此處雖然并非單行代碼,但用Ruby可以寫出更簡單的實現(xiàn):
- index = 0
- while primes[index]**2 <= primes.last
- prime = primes[index]
- primes = primes.select { |x| x == prime || x % prime != 0 }
- index += 1
- end
- p primes
***一個例子直接來自StackOverflow。雖然不是最漂亮的代碼,但提供了一種思路。
譯文鏈接:http://www.codeceo.com/article/10-ruby-oneline-code.html
英文原文:10 Ruby One Liners to Impress Your Friends