Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant chained 'or's for tests on same variable in Ruby

Tags:

ruby

What's the sensible way of saying this.

if @thing == "01" or "02" or "03" or "04" or "05"

(The numbers are contained in a column of datatype string.)

like image 698
snowangel Avatar asked Apr 21 '12 14:04

snowangel


2 Answers

Make an array and use .include?

if ["01","02","03","04","05"].include?(@thing)

If the values really are all consecutive, you can use a range like (1..5).include? For strings, you can use:

if ("01".."05").include?(@thing)
like image 73
Michael Berkowski Avatar answered Sep 23 '22 20:09

Michael Berkowski


Or use a case statement:

case @thing
when "01", "02", "03", "04", "05"
  # do your things
end

Two variations of this approach:

case @thing
when "01".."05"
  # do your things
end

case @thing
when *%w[01 02 03 04 05]
  # do your things
end

Because case uses ===, you could also write: ("01".."05") === @thing

like image 38
J-_-L Avatar answered Sep 26 '22 20:09

J-_-L