Try It Yourself!(5) I don't understand


I have the right answer for this

Define your own method, double, that accepts a single parameter and yields to a block. Then call it with a block that multiplies the number parameter by 2. You can double any number you like!

def double(x)
yield *2

double("2") { |x| puts "It's double is #{x}." }

The only thing where it says double ( ). I can place any number or a any string with a number such as 2, 10 or "2" or "10" and it says it's correct. Why is this correct?


Hey @kovothemaji

I'm suspecting the reason you get correct no matter what you're sending to the double function, is probably based on how codecademy looks for the exercise being correct. Most likely, it only checks to see if there is a method named double, it's being called with a block parameter and that something is being yielded to the block from inside the method

However, taking a look at the code you provided, I'm afraid that the code wouldn't work as the exercise wanted.

Firstly, I'm assuming that you were experimenting with sending either 2 or "2", which is why it's in the code you provided.

Secondly, the parameter that is being passed to the function, is not being passed along to the block. Instead, you're just sending the number 2 directly (adding the * in front of 2 doesn't mean multiplication, unless there's a number in front * as well. In this context, I think Ruby interprets it as the 'splat' operator, to indicate converting 2 to an array,but I can't say for certain I'm afraid).
The correct way would be to run "yield x", since x is the parameter defined in double.

Thirdly, the exercise asks for the block itself to do the multiplication, so you could for instance change the block to be { |x| puts "It's double is #{x*2}." }, where x, the value we now passed when yielding to the block, is being multiplied with 2 before it's printed.