Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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"}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement