-
-
Save crmaxx/c6ed0c5a475d58069688 to your computer and use it in GitHub Desktop.
This file contains 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
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