Handy Collect/Map Shortcut in Rails

Posted on August 13, 2007

Have an array of strings that you’d easily like to turn into an array of syms?

%w[total total_found time].map(&:to_sym)
# Result: [:total, :total_found, :time]

Have an array of arrays out of which you’d like to easily extract the first item from?

[[1, 'One'], [2, 'Two'], [3, 'Three']].map(&:first)
# Result: [1, 2, 3]

These will also work with the collect and map! functions.

More here on the map function and its origins in functional programming languages like lisp.