Ruby - Can I pass a block as a parameter as an actual block to another function?

This is what I am 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 will only output "class: Object" every time # I'm trying to get this to output "class: String" though call_block("String") { puts "class: #{self.class}" } 

In the line that says "instance.instance_eval {block.call}", I'm trying to find another way to instantiate a new instance of the instance on the block. The only way I can force this to be done is to pass an instance of the original source block, not as a variable or something else, but as a real block, as in the test example.

Any tips?

+6
ruby
source share
1 answer

Yes. You can pass a block to another method by adding a block variable with an ampersand like this:

 def foo &blk # now, blk is a variable bound to a block object bar &blk end 

The reason you get "class: Object" is because Ruby uses lexical scope. This means that self in puts "class: #{self.class}" refers to main , the default context.

+8
source share

All Articles