Ezequiel Ramiro
Ezequiel Ramiro

Reputation: 760

Ruby on rails Case when statement not working

I can't understand why my case/when statement is not working... i couldn't find much information about 'AND (&&)' operator.

points = -180
case points
 when (points >= -9999) && (points < -300) then
    title = "bad player"
 when (points >= -300) && (points < -100) then
    title = "not reliable"
 when (points >= -100) && (points < 100) then
    title = "Newbie"
end

I'm getting title = blank..

Thank you

Upvotes: 1

Views: 711

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

Try this

points = -180
case
when (points >= -9999) && (points < -300)
  title = "bad player"
when (points >= -300) && (points < -100)
  title = "not reliable"
when (points >= -100) && (points < 100)
  title = "Newbie"
end

#=> "not reliable"

You can also use range

points = -180

title = 
  case points
  when -9999..-301
    "bad player"
  when -300..-99
    "not reliable"
  when -100..99
    "Newbie"
  end


#=> "not reliable"

Upvotes: 3

ndnenkov
ndnenkov

Reputation: 36100

So you are case-ing on the points variable, but you try to do something completely different in the when clauses. At least two of the three whens will evaluate to false, the other one - possibly to true. So you are actually checking if -180 is true or false.


What you actually wanted to do was probably:

case points
when -9999...-300 then 'bad player'
when -300...-100  then 'not reliable'
when -100...100   then 'Newbie'
end

Upvotes: 1

Related Questions