Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: yield block from a block?

Tags:

ruby

lambda

Is it possible for a lambda, proc, method or other type of block in ruby, to yield to another block?
something like...

a = lambda {
  puts 'in a'
  yield if block_given?
}

a.call { puts "in a's block" }

this doesn't work... it just produces

in a
=> nil

Is there way to get the block to call a block?

like image 414
Derick Bailey Avatar asked Oct 21 '09 16:10

Derick Bailey


People also ask

How do you yield in Ruby?

To pass any argument from yield to the block we can write || inside the block as the name of the argument. {|number| puts “Your message”} and yield will call as yield 5. So here 5 will be the value for the |number|.

Does yield return Ruby?

The yield keyword instructs Ruby to execute the code in the block. In this example, the block returns the string "yes!" .

What is &Block in Ruby?

The &block is a way of sending a piece of Ruby code in to a method and then evaluating that code in the scope of that method.

How does yield work in Ruby on Rails?

Yield is a keyword (meaning it's a core part of the language) & it's used inside methods for calling a block. Here's what you need to know: Calling a block runs the code inside that block (like calling a method) Yield can pass any number of arguments to the block.


2 Answers

I'm not sure if you can you can do that, but something similar would be:

In Ruby 1.8.6:

a = lambda { |my_proc|
  puts 'in a'
  my_proc.call
}

a.call(lambda { puts "in a's block" })

In Ruby 1.9.1, you can have block parameters

a = lambda { |&block|
  puts 'in a'
  block.call
}

a.call { puts "in a's block" }
like image 72
ottobar Avatar answered Oct 17 '22 04:10

ottobar


You can call the block, which is similar to yielding.

a = lambda {|&block| block.call if block}
a.call {print "hello"}

Note that

a.call

Will not return an error.

like image 41
jrhicks Avatar answered Oct 17 '22 04:10

jrhicks