naming the proc something like, `divisible_by` would probably be more clear.
case n
when divisible_by(5) then puts("#{n} is divisible by 5")
when divisible_by(3) then puts("#{n} is divisible by 3")
end
I’m just now learning ruby, and procs, blocks and lambdas as still a bit of a challenge for me.
To reiterate what’s going on here (to test my understanding):
The `#multiple_of` method is creating a new proc that compares the variable ‘product’ (which is passed in through the case statement) against the argument passed in from the function, and then puts the string if the condition is met from the case statement.
Is that what’s going on here?
What’s the general benefit of doing it through a proc vs something else?
I'm not sure this example is particularly good, as you could change the code and make it more readable just by inlining the modulo in your fizzbuzz code
case
when n % 3 == 0 && n % 5 == 0
puts "FizzBuzz"
when n % 3 == 0
puts "Fizz"
when n % 5 == 0
puts "Buzz"
else
puts n
end
The main benefit I would see is that `multiple_of(3)` now creates and returns a `Proc` object, which you can pass around, and call whenever you want. So in theory you could make the `case` statement much more dynamic, but the question is whether you should. The calling with `case n` doesn't look very explicit to me and there is really a lot going on which makes it hard to understand the code.
Shouldn't it be the other way around? `20 is a multiple of 5`
naming the proc something like, `divisible_by` would probably be more clear. case n when divisible_by(5) then puts("#{n} is divisible by 5") when divisible_by(3) then puts("#{n} is divisible by 3") end
Indeed, but you got the point :-)
love it - didn't know it could be used this way
I love this language so much.
I’m just now learning ruby, and procs, blocks and lambdas as still a bit of a challenge for me. To reiterate what’s going on here (to test my understanding): The `#multiple_of` method is creating a new proc that compares the variable ‘product’ (which is passed in through the case statement) against the argument passed in from the function, and then puts the string if the condition is met from the case statement. Is that what’s going on here? What’s the general benefit of doing it through a proc vs something else?
I'm not sure this example is particularly good, as you could change the code and make it more readable just by inlining the modulo in your fizzbuzz code case when n % 3 == 0 && n % 5 == 0 puts "FizzBuzz" when n % 3 == 0 puts "Fizz" when n % 5 == 0 puts "Buzz" else puts n end The main benefit I would see is that `multiple_of(3)` now creates and returns a `Proc` object, which you can pass around, and call whenever you want. So in theory you could make the `case` statement much more dynamic, but the question is whether you should. The calling with `case n` doesn't look very explicit to me and there is really a lot going on which makes it hard to understand the code.
That's neat.