Skip to content

Instantly share code, notes, and snippets.

@jamiew
Created April 19, 2012 20:32
Show Gist options
  • Save jamiew/2423961 to your computer and use it in GitHub Desktop.
Save jamiew/2423961 to your computer and use it in GitHub Desktop.
each vs map usage in ruby
json = ActiveSupport::JSON.decode(google)['predictions']
# sort of traditional for() loop style
results = []
json.each do |location|
results << {
:short => 'foo',
:long => 'bar'
}
end
# functional programming style
# in ruby you never actually need to use the 'return' keyword,
# in neither a def foobar; ...; end" method or an anonymous block like this
# the last value is always returned
results = json.map do |location|
{
:short => 'foo',
:long => 'bar'
}
end
# or also like this
# writing with smaller methods makes it easier to unit test
def short_and_long_from_location(location)
{
:short => 'foo',
:long => 'bar'
}
end
results = json.map {|loc| short_and_long_from_location(loc) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment