Ruby’s block/closure support
I’ve been playing around with Ruby lately, because I hear it’s an interesting scripting language. Like many other people, I have enjoyed the block/closure support that the language offers. For example, when creating an array, you can pass a block to the constructor to populate the Array’s values. So, if you wanted to populate an array initially with integers equal to the indices at which they occur, in Java you would have to write
int[] order = new int[52]; for(int i=0; i < order.length; i++) { order[i] = i; }
whereas in Ruby you just write
order = Array.new { |i| i }
Another nice example of block usage is the following way to “shuffle” an array:
a.sort_by { rand }
where rand returns a random number between 0 and 1. In this case, the output of the block returns the value by which sort_by sorts for each element of the array. In general this seems to lead to much more compact code that is still readable.
A multiline block is specified like so:
a.collect do |element| if element=="capitalize me" return element.upcase else return element.downcase end end
That code returns an array of the elements of a with the block applied to each one. Note that you can eliminate the uses of return, because those lines are the last expressions evaluated inside the block. Thus, a more Ruby-like way to write the above would be:
a.collect do |element| if element=="capitalize me" element.upcase else element.downcase end end