December 01, 2011

Ruby: Do Something To X Items With first(x)

Learning Ruby (even after a year-and-some I’m constantly learning) means I get to enjoy a lot of Holy Shit That Was So Easy! moments like this one.

I had an array that I wanted to just grab the first few items from and perform an operation on them. (In this case, I was taking an array of country codes, which could be any length, and displaying the full names of the first three using the Carmen gem to map codes to country names.) My first thought was to loop through the whole array using each_with_index and just perform the operation to the first three. Or, since that’s really inefficient, wrap it in 3.times do so it doesn’t have to loop through the whole array. first(x) is actually even more concise than either of those solutions:

array.first(3).each do |c|
  c = Carmen::country_name(c)

Or even sweeter, in just one line:

array.first(3).map {|c| Carmen::country_name(c)}