Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby pass arguments to block

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.

like image 321
mike Avatar asked Feb 11 '26 07:02

mike


1 Answers

...
  #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"
like image 70
DNNX Avatar answered Feb 15 '26 12:02

DNNX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!