Victor
Victor

Reputation: 13378

Why does this case statement only evaluate the else clause?

Using Rails 3, but I guess doesn't matter. I put this in the template helper.

It always goes to the last case badge-warning when I for whatever value I put for rating, such as rating_badge(4):

  def rating_badge(rating)
    case rating
    when rating > 3
      'badge-success'
    when rating < 3
      'badge-important'
    else
      'badge-warning'
    end
  end

What went wrong?

Upvotes: 0

Views: 89

Answers (3)

Andr&#233; Medeiros
Andr&#233; Medeiros

Reputation: 810

If you supply a variable to case, it will try and match the variable's value against each value supplied to when statements. As you put a condition after each when, it will first evaluate the condition and then match it against rating. However, the evaluation will ONLY produce true or false and as apparently you provide a numerical value to case, it will ALWAYS fall to else case (as rating is never true nor false).

The correct syntax has already been posted by @CodeGnome, but I think you should know the reasons to this failure!

:)

Upvotes: 0

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84373

You have a stray rating variable at the top of your case statement. The correct syntax is:

case
when rating > 3
  'badge-success'
when rating < 3
  'badge-important'
else
  'badge-warning'
end

This works for me at the REPL using pry and irb.

Upvotes: 7

gabrielhilal
gabrielhilal

Reputation: 10769

I don't know the syntax for case, I think you must include the word then...

when something then result1
when something_else then result2
...

But you can achieve the same result using if:

def rating_badge(rating)
  if rating > 3
   'badge-success'
  elsif rating < 3
    'badge-important'
  else
    'badge-warning'
  end
end

Upvotes: 1

Related Questions