将变量与Ruby中的两个不同值进行比较

von*_*rad 4 ruby

这更像是语义问题而不是其他问题.

我想检查一个变量是否是两个值之一.最简单的方法是:

if var == "foo" || var == "bar"
# or
if var == 3     || var == 5
Run Code Online (Sandbox Code Playgroud)

但这对我来说并不是很干涩.我知道我可以使用String.match(),但这对非字符串变量不起作用,速度慢三倍.

有没有更好的方法来检查两个值的变量?

bry*_*sai 14

将所有值放入数组中然后应该很容易.

%w[foo bar].include?('foo') # => true

[3,5].include?(3) # => true
Run Code Online (Sandbox Code Playgroud)

  • 缺少 if 语句... if(%w[foo bar].include?(var)) (2认同)

Aid*_*lly 5

case声明似乎做你想要什么.

case var
  when "foo", "bar" then case1()
end

case var
  when 3, 5 then case2()
end
Run Code Online (Sandbox Code Playgroud)

基于数组的方法似乎比这慢.