instance-eval

Why does the second 'p arg' report the Foo instance?

class Foo def with_yield yield(self) end def with_instance_eval(&block) instance_eval(&block) end end f = Foo.new f.with_yield do |arg| p self # => main p arg # => #<Foo:0x100124b10> end f.with_instance_eval do |arg| p self # => #<Foo:0x100124b10> p arg # => #<Foo:0x100124b10> end Why does the second...

ruby metaprogramming - yield block not working in dynamically added method

I'm working on extending the NotAMock framework for stubbing methods in rspec, and getting the stubs to yield to a methods block. The code in this Gist works perfectly when I code it on my own (which is done-up to resemble how NotAMock stubs methods). but when I incorporate the object.instance_eval... code into the NotAMock framework, ...

Ruby - Possible to pass a block as a param as an actual block to another function?

This is what I'm trying to do: def call_block(in_class = "String", &block) instance = eval("#{in_class}.new") puts "instance class: #{instance.class}" instance.instance_eval{ block.call } end # --- TEST EXAMPLE --- # This outputs "class: String" every time "sdlkfj".instance_eval { puts "class: #{self.class}" } # This wil...

Ruby: how does constant-lookup work in instance_eval/class_eval?

I'm working my way through Pickaxe 1.9, and I'm a bit confused by constant-lookup in instance/class_eval blocks. I'm using 1.9.2. It seems that Ruby handles constant-lookup in *_eval blocks the same way it does method-lookup: look for a definition in receiver.singleton_class (plus mixins); then in receiver.singleton_class.superclass (...

Accessing Ruby Class Variables with class_eval and instance_eval

I have the following: class Test @@a = 10 def show_a() puts "a: #{@@a}" end class << self @@b = '40' def show_b puts "b: #{@@b}" end end end Why does following work: Test.instance_eval{show_b} b: 40 => nil But I can't access @@b directly? Test.instance_eval{ @@b } NameError: uni...

Instance Eval in Javascript around browsers

From Coffeekup and JAML's source, (while working on question), we can see a way to hack ruby's instance eval into Javascript (JAML author explains more). It involves decompiling the function, and evaluating it around a with block. The question is: is this supported all around browsers/js runtimes? I know it works on firefox, opera and c...