A brief description of the Ruby case, including include? Will not work

I have the following code with a small error in it, the case statement returns the value “other”, even if the first operator “when” evaluates to true and should return “boats”.

I've been looking at this for ages, it 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

Thank!

+5
source share
3 answers

An operator is caseusually an abbreviation for an operator if. Yours can be rewritten as:

if CATEGORY_CLASSES[:boats].include?(category_id) === category_id
  category = "boats"
elsif CATEGORY_CLASSES[:houses].include?(category_id) === category_id
  category = "houses"
else
  category = "other"
end

When you look at it in this form, you must clearly understand the problem; while it include?returns a boolean, you compare it with an integer value.

+11

:

category = case category_id
  when *CATEGORY_CLASSES[:boats]; "boats"
  when *CATEGORY_CLASSES[:houses]; "houses"
  else "other"
end
+39

( , , , , , . , .) >

, , case. case, if s. when - === case. , CATEGORY_CLASSES[:boats].include?(category_id), if true === category_id, if false === category_id ( include? true false).

, , CATEGORIES.find {|k,v| v.include? category_id}.first.to_s.

+7

All Articles