Skip to content

Instantly share code, notes, and snippets.

@samsm
Last active December 14, 2015 20:19
Show Gist options
  • Save samsm/5143270 to your computer and use it in GitHub Desktop.
Save samsm/5143270 to your computer and use it in GitHub Desktop.
Ruby instance_eval scope issue I don't understand.
module Bar
module Baz
end
def hi_there
puts 'Hi!!'
end
end
class Foo
include Bar
def initialize(&block)
puts "Baz is available in this context: #{Baz.inspect}"
instance_eval(&block)
end
end
Foo.new do
hi_there
puts "Global reference works ok: #{Bar::Baz.inspect}"
puts "Why isn't Baz found? #{Baz.inspect}" # NameError: uninitialized constant Baz
end
@erik-megarad
Copy link

instance_eval only changes self. All non-instance variables (incl classes/modules) are not affected and retain the binding of when the block was defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment