Archive for the ‘Ruby’ Category


Ruby and elegance: Transpose

March 10, 2007

I recently found that the Array class of Ruby has a zip method, which works much like Haskell’s zip function, except that it allows multiple arguments.

For example:

$ irb --simple-prompt
>> [1,2,3].zip [4,5,6], [7,8,9]
=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

The night after I did this little experiment I suddenly realized: this is a transpose function! I quickly got out of bed to document my little discovery:

def transpose(matrix)
matrix[0].zip *matrix[1..-1]

It’s the little things that make me like this language so much.

Update: I forgot the asterisk before matrix[1..-1] in the above method.


Summing it up

February 24, 2007

Today, I had a list of integers, and I wanted to sum it up. I guessed that I should write a script in Ruby, to make sure it would get done within 2 minutes. So I fired up my editor, and wrote the following script:

sum = 0 ;
$stdin.each do |line|
puts sum

Pretty straightforward. I’d rather had written the script in Haskell, but I figured I needed to get things done. This evening I tried the same thing in Haskell, but to I was surprised: it was even quicker and more straightforward than the Ruby version! Here it is:

main = interact $ show . sum . map read . lines

If you’d like more of these tiny tools, see Haskell Unix Tools.