Skip to content

Instantly share code, notes, and snippets.

@crmaxx
Forked from cupakromer/gist:3371003
Last active August 29, 2015 14:22
Show Gist options
  • Save crmaxx/c6ed0c5a475d58069688 to your computer and use it in GitHub Desktop.
Save crmaxx/c6ed0c5a475d58069688 to your computer and use it in GitHub Desktop.
my_array = %w[test one two three]
# Inject takes the value of the block and passes it along
# This often causes un-intended errors
my_array.inject({}) do |transformed, word|
puts transformed
transformed[word] = word.capitalize
end
# Output:
# {}
# Test
# IndexError: string not matched
# from (pry):6:in `[]='
# What was really wanted was:
my_array.inject({}) do |transformed, word|
puts transformed
transformed[word] = word.capitalize
transformed
end
# Output:
# {}
# {"test"=>"Test"}
# {"test"=>"Test", "one"=>"One"}
# {"test"=>"Test", "one"=>"One", "two"=>"Two"}
=> {"test"=>"Test", "one"=>"One", "two"=>"Two", "three"=>"Three"}
# On the other hand, each_with_object does exactly as you expect
# It ignores the return value of the block and only passes the
# initial object along
my_array.each_with_object({}) do |word, transformed|
puts transformed
transformed[word] = word.capitalize
"this is ignored"
end
# Output:
# {}
# {"test"=>"Test"}
# {"test"=>"Test", "one"=>"One"}
# {"test"=>"Test", "one"=>"One", "two"=>"Two"}
=> {"test"=>"Test", "one"=>"One", "two"=>"Two", "three"=>"Three"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment