James Andino
James Andino

Reputation: 25779

Ruby passing blocks to blocks

(1..5).each do|x| puts yield(x) end do |x| return x*2 end

In my head this would loop 1 through 5 call the first block that would yield to the second block and put 2,4,6,8,10

Why does this not work and whats the easiest way to write this.

Upvotes: 0

Views: 133

Answers (2)

seph
seph

Reputation: 6076

The easiest way to write this:

(1..5).each { |x| puts x*2 }

Upvotes: 1

Dmitry Maksimov
Dmitry Maksimov

Reputation: 2861

yield works within the methods. Quote from "Programming Ruby":

Within the method, the block may be invoked, almost as if it were a method itself, using the yield statement.

So, if you want to make this code working, you can change it to something like this:

def f(n)
  (1..n).each do |x|
    puts yield(x)
  end
end

f(5) do |x|
  x * 2
end

If you don't want to define method you should put block into the variable and then use it:

b = Proc.new{|x| x *2 }

(1..5).each do |x|
  puts b.call(x)
end

Upvotes: 3

Related Questions