这是一个有效的ruby语法吗?

时间:2009-10-28 02:14:30

标签: ruby

if step.include? "apples" or "banana" or "cheese"
say "yay"
end

8 个答案:

答案 0 :(得分:6)

您的代码有几个问题。

step.include? "apples" or "banana" or "cheese"

此表达式的计算结果为:

step.include?("apples") or ("banana") or ("cheese")

由于Ruby将falsenil以外的所有值视为true,因此该表达式始终为true。 (在这种情况下,值"banana"short-circuit表达式并使其评估为true,即使step的值不包含这三个中的任何一个。)

你的意图是:

step.include? "apples" or step.include? "banana" or step.include? "cheese"

然而,这是低效的。它还使用or代替||,它具有不同的运算符优先级,通常不应在if条件中使用。

正常or用法:

do_something or raise "Something went wrong."

更好的写作方式是:

step =~ /apples|banana|cheese/

这使用regular expression,你将在Ruby中使用很多。

最后,除非你定义一个方法,否则Ruby中没有say方法。通常,您可以通过调用puts打印一些内容。

所以最终的代码如下:

if step =~ /apples|banana|cheese/
  puts "yay"
end

答案 1 :(得分:3)

Ruby的最后两个术语似乎是真的,而不是与include?短语有任何关系。

假设step是一个字符串...

step = "some long string with cheese in the middle"

你可以写这样的东西。

puts "yay" if step.match(/apples|banana|cheese/)

答案 2 :(得分:2)

这是一种在每个参数上调用step.include?的方法,直到其中一个返回true

if ["apples", "banana", "cheese"].any? {|x| step.include? x}

答案 3 :(得分:1)

这绝对不是你想要的。 include?方法接收String,而不是"apples" or "banana" or "cheese"生成的内容。试试这个:

puts "yay" if ["apples", "banana", "cheese"].include?(step)

但从背景中不清楚应该采取什么步骤。如果它只是单个单词,那么这很好。如果它可以是一个完整的句子,请尝试joel.neely的答案。

答案 4 :(得分:1)

最接近你想要的语法就是:

  if ["apples", "banana", "cheese"].include?(step)
    puts "yay"
  end

但使用正则表达式的其他建议之一将更简洁和可读。

答案 5 :(得分:1)

假设stepArraySet或支持与&运算符设置交集的其他内容,我认为以下代码是最惯用的:< / p>

unless (step & ["apples","banana","cheese"]).empty?
  puts 'yay'
end

答案 6 :(得分:0)

我会为你添加一些括号:

if (step.include? "apples") or ("banana") or ("cheese")
    say "yay"
end

(这就是为什么它总是说“yay” - 因为表达总是正确的。)

答案 7 :(得分:-1)

只是为此添加另一面......

如果step Array(正如调用include?似乎建议的那样)那么代码应该是:

if (step - %w{apples banana cheese}) != step
  puts 'yay'
end