Created
April 19, 2012 20:32
-
-
Save jamiew/2423961 to your computer and use it in GitHub Desktop.
each vs map usage in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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