Skip to content

Instantly share code, notes, and snippets.

@calebhearth
Created August 7, 2012 21:37
Show Gist options
  • Save calebhearth/3289590 to your computer and use it in GitHub Desktop.
Save calebhearth/3289590 to your computer and use it in GitHub Desktop.
The Dangers of Ruby 'for' and metaprogramming
THINGS = %w{ foo bar baz }
class EachThing
THINGS.each do |thing|
define_method(thing) { thing }
end
end
class ForThing
for thing in THINGS do
define_method(thing) { thing }
end
end
puts "============EACH==========="
puts "foo: #{ EachThing.new.foo }"
puts "bar: #{ EachThing.new.bar }"
puts "baz: #{ EachThing.new.baz }"
puts "============FOR============"
puts "foo: #{ ForThing.new.foo }"
puts "bar: #{ ForThing.new.bar }"
puts "baz: #{ ForThing.new.baz }"
============EACH===========
foo: foo
bar: bar
baz: baz
============FOR============
foo: baz
bar: baz
baz: baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment