I have the following code
class SomeClass
#define method, which take block and save it into class variable
def self.test(&block)
@@block = block
end
#pass block to method
test do |z|
p self
p z
end
#call block with argument and change context
def call_block(arg)
block = @@block
instance_eval &block.call(arg)
end
end
s = SomeClass.new
s.call_block("test")
I got output
SomeClass # Why not instance?
"test"
4.rb:14:in `call_block': wrong argument type String (expected Proc) (TypeError)
from test.rb:20:in `<main>'
Why are the result? How to change scope from SomeClass to SomeClass instance ?
UPD:
Error because block return String but must be return block or lambda or proc.
...
#call block with argument and change context
def call_block(arg)
block = @@block
instance_exec(arg, &block)
end
end
s = SomeClass.new
s.call_block("test")
#<SomeClass:0x10308ad28>
"test"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With