Skip to content
Tags

,

10 ruby one liners

June 2, 2011

The following blog entry is pasted from here:

http://programmingzen.com/2011/06/02/10-ruby-one-liners-to-impress-your-friends/

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 Symbol#to_proc syntax available (built-in) 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
p primes
Advertisements

From → Uncategorized

One Comment
  1. Hi Antonio,

    I am the one who wrote the unreadable article you mention 🙂

    Regular expressions are just very complex to explain. Especially /^1?$|^(11+?)\1+$/ which, for some people, including myself initially, which looks more like a bunch of random symbols than something meaningful 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: