Advertisement
Guest User

Untitled

a guest
Jul 1st, 2015
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. my_array = %w[test one two three]
  2.  
  3. # Inject takes the value of the block and passes it along
  4. # This often causes un-intended errors
  5. my_array.inject({}) do |transformed, word|
  6. puts transformed
  7. transformed[word] = word.capitalize
  8. end
  9. # Output:
  10. # {}
  11. # Test
  12. # IndexError: string not matched
  13. # from (pry):6:in `[]='
  14.  
  15. # What was really wanted was:
  16. my_array.inject({}) do |transformed, word|
  17. puts transformed
  18. transformed[word] = word.capitalize
  19. transformed
  20. end
  21. # Output:
  22. # {}
  23. # {"test"=>"Test"}
  24. # {"test"=>"Test", "one"=>"One"}
  25. # {"test"=>"Test", "one"=>"One", "two"=>"Two"}
  26. => {"test"=>"Test", "one"=>"One", "two"=>"Two", "three"=>"Three"}
  27.  
  28.  
  29. # On the other hand, each_with_object does exactly as you expect
  30. # It ignores the return value of the block and only passes the
  31. # initial object along
  32.  
  33. my_array.each_with_object({}) do |word, transformed|
  34. puts transformed
  35. transformed[word] = word.capitalize
  36. "this is ignored"
  37. end
  38. # Output:
  39. # {}
  40. # {"test"=>"Test"}
  41. # {"test"=>"Test", "one"=>"One"}
  42. # {"test"=>"Test", "one"=>"One", "two"=>"Two"}
  43. => {"test"=>"Test", "one"=>"One", "two"=>"Two", "three"=>"Three"}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement