【发布时间】:2018-04-22 11:34:19
【问题描述】:
想知道有没有办法压缩这行代码:
elsif i == '+' || i == '-' || i == '/' || i == '*'
【问题讨论】:
标签: ruby if-statement conditional
想知道有没有办法压缩这行代码:
elsif i == '+' || i == '-' || i == '/' || i == '*'
【问题讨论】:
标签: ruby if-statement conditional
case when 控制结构允许这样的压缩线:
case i
when '+', '-', '/', '*' # <= condensed line of code
puts "operator!"
end
【讨论】:
when /[-+\/*]/。
你可以这样做
"+-/*".include?(i)
【讨论】:
类似于@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
【讨论】: