# 10 times 2 = 27?

#1

I just discovered yield and I am trying ot understand how it works and why it is useful (so far I don’t!)
I tried this today but I get a really weird result !

How does multiplying 10 by 2 give 27?

``````

def double (parameter)
parameter *2
yield
end

puts double(10) {puts "this is in a block"}

# => this is in a block
# => 27

``````

#2

Running your code will get a nil value followed by “this is in a block” I have no idea where that 27 came from.

Look at this function

`````` def feed_the_block(number)
yield number
end
``````

now we give our function a block to “feed numbers to”

``````feed_the_block(7) {|x| x * 2}
``````

We fed the block a 7 as its block argument, then the block executed it’s code against the argument we fed it.
Our output is 14

``````def double(parameter)
parameter *= 2
yield parameter
end
``````

We have a function that takes a parameter, doubles it and feeds the result to a block

`double(10) {|x| x + 5}`
Take ten, double it and yield it to a block
Our output 25

Hope this helps

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.