Skip to content

Instantly share code, notes, and snippets.

@carlosbrando
Created February 4, 2011 02:58
Show Gist options
  • Save carlosbrando/810670 to your computer and use it in GitHub Desktop.
Save carlosbrando/810670 to your computer and use it in GitHub Desktop.
Context Probe
class Myclass
def initialize
@v = 1
end
end
obj = Myclass.new
obj.instance_eval do
p self
p @v # => 1
end
v = 2
# posso acessar variáveis dos dois escopos através do instance_eval
obj.instance_eval { @v = v }
obj.instance_eval { p @v } # => 2
#########################
# Somente para o Ruby 1.9
class C
def initialize
@x, @y = 1, 2
end
end
# posso passar um argumento
p C.new.instance_exec(3) { |arg| (@x + @y) * arg } # => 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment