10 neat Ruby one liners

Marcus Kazmierczak came up with a list of 10 one-liner examples that are meant to showcase Scala’s expressiveness . A [CoffeeScript version]http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html) quickly emerged, and now a Ruby one

Multiply each item in a list by 2

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

Sum a list of numbers

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

Or using the (built in) Symbol#to_proc syntax that’s been available since Ruby 1.8.7:

(1..1000).inject(&:+)

Or even just passing a symbol directly:

(1..1000).inject(:+)

Verify if tokens exist in a string

words = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."

words.any? { |word| tweet.include?(word) }

Reading a file

file_text = File.read("data.txt")
file_lines = File.readlines("data.txt")
The latter includes “\n” at the end of each element of the array, which can be trimmed by appending .map { str str.chop } or by using the alternative version:
File.read("data.txt").split(/\n/)

Happy Birthday

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

Filter a list of numbers

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

Fetch and parse an XML web service

require 'open-uri'
require 'hpricot'

results = Hpricot(open("http://search.twitter.com/search.atom?&q=scala"))

This example requires open-uri and hpricot or equivalent libraries (you could use builtin ones if you wish). It’s not too much code, but Scala clearly wins here.

Find minimum (or maximum) in a list

[14, 35, -7, 46, 98].min
[14, 35, -7, 46, 98].max

Parallel Processing

require 'parallel'
Parallel.map(lots_of_data) do |chunk|
      heavy_computation(chunk)
end

Unlike Scala, multicore support is not built-in. It requires parallel or a similar gem.

Sieve of Eratosthenes

The Scala one liner is very clever, but entirely unreadable. A simpler implementation that is no longer a one-liner in Ruby would be:

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

This last example is straight from StackOverflow . Not the prettiest code ever, but you get the idea.

-Matt

03 Jun 2011