Skip to content

Instantly share code, notes, and snippets.

@jedschneider
Created November 4, 2012 15:46
Show Gist options
  • Select an option

  • Save jedschneider/4012349 to your computer and use it in GitHub Desktop.

Select an option

Save jedschneider/4012349 to your computer and use it in GitHub Desktop.
# using each with object, no return necessary
irb(main):003:0> [:first_name, :last_name].each_with_object({}) {|x, m| m[x] = x }
=> {:first_name=>:first_name, :last_name=>:last_name}
irb(main):004:0>
# using inject
# doesn't work, without expressly returning memo
irb(main):001:0> [:first_name, :last_name].inject({}){|m, x| m[x] = x }
NoMethodError: undefined method `[]=' for :first_name:Symbol
from (irb):1:in `block in irb_binding'
from (irb):1:in `each'
from (irb):1:in `inject'
from (irb):1
from /Users/jed/.rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>'
irb(main):002:0> [:first_name, :last_name].inject({}){|m, x| m[x] = x ; m}
=> {:first_name=>:first_name, :last_name=>:last_name}
# using tap
irb(main):004:0> [:first_name, :last_name].inject({}) {|m, x| m.tap { m[x] = x } }
=> {:first_name=>:first_name, :last_name=>:last_name}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment