压缩几个比较相同值的条件语句

Condense several conditional statement comparing the same value

想知道有没有办法把这行代码压缩一下:

elsif i == '+' || i == '-' || i == '/' || i == '*'

你可以做到

"+-/*".include?(i)

一个case when控制结构允许这样一个浓缩的行:

case i
when '+', '-', '/', '*'  # <= condensed line of code
  puts "operator!"
end

与@Subash 类似,但您也可以这样做,因为:

#this returns the match string of i which is truthy or false if no match.

elsif "+-/*"[i] 

如果你想 return 布尔值 true 或 false 你也可以双 bang

elsif !!"+-/*"[i] #true if matched, false if not

在 ruby 中有许多变体,如果您有正则表达式或其他类型的字符串匹配,您也可以使用

i = '/'
!!"+-/*".match(i) #true