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

时间:2018-04-22 11:34:20

标签: ruby if-statement conditional

我想知道是否有办法压缩这行代码:

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

3 个答案:

答案 0 :(得分:5)

case when控件结构允许这样的浓缩线:

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

答案 1 :(得分:3)

你可以做到

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

答案 2 :(得分:0)

与@Subash相似,但您也可以这样做:

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

elsif "+-/*"[i] 

如果你想返回布尔值true或false,你也可以双击

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

在ruby中有很多这种变体,如果你有一个正则表达式或其他类型的字符串匹配,你也可以使用

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