Skip to content

Instantly share code, notes, and snippets.

@davestevens
Created January 19, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davestevens/9d60e389892f740e3e42 to your computer and use it in GitHub Desktop.
Save davestevens/9d60e389892f740e3e42 to your computer and use it in GitHub Desktop.
Inject vs. Each With Object
#!/usr/bin/env ruby
inputs = [[1,2,3], [2,4,6], [1,3,5]]
inject_output = inputs.inject([]) do |memo, input|
memo |= input
memo
end
each_with_object_output = inputs.each_with_object([]) do |input, memo|
memo |= input
# puts memo.inspect
# Expected output from puts
## 1: [1, 2, 3]
## 2: [1, 2, 3, 4, 6]
## 3: [1, 2, 3, 4, 5, 6]
end
# Expected output => [1, 2, 3, 4, 5, 6]
puts inject_output.inspect # => [1, 2, 3, 4, 5, 6]
puts each_with_object_output.inspect # => []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment