10个惊艳的Ruby单行代码

1.数组中的每个元素乘以2

(1..10).map { |n| n * 2 }

2.数组中的元素求和

(1..1000).inject { |sum, n| sum + n }

或使用(内置的)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”在数组每个元素的末端,它可以通过附加 .map { |str| str.chop } 或者使用替代版本来做修整:

File.read("data.txt").split(/\n/)

5.生日快乐

4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" }

6.过滤数组中的数字

[49, 58, 76, 82, 88, 90].partition { |n| n > 60 }

7.获取并解析一个XML Web服务

require 'open-uri'require 'hpricot'results = Hpricot(open("http://search.twitter.com/search.atom?&q=scala"))

这个例子需要open-uri或hpricot或等效库(如果你愿意,你可以使用内置的)。没有太多的代码,但Scala在这里明显胜出。

8.在数组中查找最小(或最大)值

[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,多核支持不是内置的。它需要parallel 或类似的东西。

10.埃拉托斯特尼筛法

Scala的单行代码很聪明,但完全不可读。此处虽然并非单行代码,但用Ruby可以写出更简单的实现:

index = 0while primes[index]**2 <= primes.last      prime = primes[index]      primes = primes.select { |x| x == prime || x % prime != 0 }      index += 1endp primes

最后一个例子直接来自StackOverflow。虽然不是最漂亮的代码,但提供了一种思路。

猜你喜欢

转载自pda158.iteye.com/blog/2299659