Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Ruby Case Statement using include? Will Not Work

Tags:

ruby

case

I have the following code with a small bug in it, the case statement returns the value "other" even though the first "when" statement evaluates true and should return "boats".

I've been been looking at this for ages, must be something small.

CATEGORIES = {:boats  => [1, 2, 3, 4, 5, 6],
              :houses => [7, 8, 9, 10],
              :other  => [11,12,13,14,15,16]
             }

category_id = 1

category = case category_id
  when CATEGORY_CLASSES[:boats].include?(category_id); "boats"
  when CATEGORY_CLASSES[:houses].include?(category_id); "houses"
  else "other"
end

Thanks!

like image 512
Jason Avatar asked Oct 04 '10 17:10

Jason


People also ask

Can you use || IN case statement Ruby?

If you are eager to know how to use an OR condition in a Ruby switch case: So, in a case statement, a , is the equivalent of || in an if statement.

What is a case statement in Ruby?

The case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression.

Does Ruby case fall through?

It does not fall through. Ruby just doesn't have the same behavior as Java for this type of statement.


1 Answers

You can expand array in when statement as follows:

category = case category_id
  when *CATEGORY_CLASSES[:boats]; "boats"
  when *CATEGORY_CLASSES[:houses]; "houses"
  else "other"
end
like image 121
ebsbk Avatar answered Sep 30 '22 08:09

ebsbk