Case Statement in Method - Ruby


(Matthew Matt) #1

If I have a method with a case statement like this:

def output(p1, p2, p3)
    when counts[:p1] == 5 then "P1 won this game!!"
    when counts[:p2] == 5 then "P2 won this game!"
    when win?(p1, p3) then "P3 won this round!"
    when win?(p2, p1) then "P2 won this round! You loose!"
    else "It's a tie on this round! No one wins!"

What would be the name of the case then?

(jms) #2

Well @MatthewMatt the good thing about Ruby is it evaluates everything to Object, So at the end your case statement no matter how advanced it is, will result in a an object being passed as parameter to the prompt() procedure.

Ruby decides which result to pass as an object depending on which instruction line is executed last (at which when clause).

(SAM) #3

I never knew (passing a Case block as method parameter in ruby) should be called anything else other than ‘Case’.

Anyway @MatthewMatt it would be really interesting to know what is called (though I googled and found no reference on that).

(Tas Dever) #4

A Parameter?!!

In that code snippet the Case block is given as Parameter, or in fact to be more specific as @jms said. The case resulting object value is used as Parameter for your prompt() method.

Though i am not quite sure, i know what you meant by that question?!

  • Should we name the Case?
    Hmm… I don’t think it can be named anything else other than “case”, as Python unfinished docs do not really call it anything specific, and I can’t see why they should.

  • The way case syntax is formatted not the way it’s passed to prompt()
    In case that’s what you meant I see your Case statement is parameter-less. Which is similar to multiple If/else statements. And it’s completely fine & supported starting from Ruby version 1.9+.

  • Resulting Value
    The case statement you presented, will always result in a String being passed as parameter to the prompt() method.

_If this doesn't help; I really which you can present more information, and maybe clarify your question/intention a bit._