p (1..10).map {|n| n*2}
p (1..1000).inject { |sum, n| sum + n }
或者使用自Ruby1.8.7以来Symbol#to_proc语法:
p (1..1000).inject(&:+)
或者直接写成symbol:
p (1..1000).inject(:+)
译者注: 在Rails中,更简单的写法:
(1..1000).sum
words = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." p words.any? { |word| tweet.include?(word) }
p file_text = File.read("data.txt") p file_lines = File.readlines("data.txt")
如果希望过滤行尾的“\n”,我们可以写使用 .map { |str| str.chop } 截取行尾,或者直接使用split这么写:
p File.read("data.txt").split(/\n/)
4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" }
p [49, 58, 76, 82, 88, 90].partition { |n| n > 60 }
require 'rubygems' require 'open-uri' require 'hpricot' results = Hpricot(open("https://cnos.info/proxy/index.php?q=aHR0cDovL3NlYXJjaC50d2l0dGVyLmNvbS9zZWFyY2guYXRvbT8mYW1wO3E9cHl0aG9u&hl=3ed")) p results
p [14, 35, -7, 46, 98].min p [14, 35, -7, 46, 98].max
这里Ruby做不到一行处理,需要使用parallel
require 'rubygems' require 'parallel' Parallel.map(lots_of_data) do |chunk| heavy_computation(chunk) end
埃拉托斯特尼筛法,简称埃氏筛或爱氏筛,是一种公元前250年由古希腊数学家埃拉托斯特尼所提出的一种简单检定素数的算法。
#参考wikipedia,求120以内的素数 n=120 primes = Array.new for i in 0..n-2 primes[i] = i+2 end 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