if step.include? "apples" or "banana" or "cheese"
say "yay"
end
Run Code Online (Sandbox Code Playgroud)
您的代码有几个问题.
step.include? "apples" or "banana" or "cheese"
Run Code Online (Sandbox Code Playgroud)
此表达式的计算结果为:
step.include?("apples") or ("banana") or ("cheese")
Run Code Online (Sandbox Code Playgroud)
因为Ruby会将除了false和之外的所有值都nil视为真,因此该表达式将始终为true.(在这种情况下,该值"banana"将使表达式短路并使其评估为true,即使step的值不包含这三个中的任何一个.)
你的意图是:
step.include? "apples" or step.include? "banana" or step.include? "cheese"
Run Code Online (Sandbox Code Playgroud)
但是,这是低效的.它也使用or而不是||,它具有不同的运算符优先级,通常不应该在if条件语句中使用.
正常or使用:
do_something or raise "Something went wrong."
Run Code Online (Sandbox Code Playgroud)
写这个的更好方法是:
step =~ /apples|banana|cheese/
Run Code Online (Sandbox Code Playgroud)
这使用了一个正则表达式,你将在Ruby中大量使用它.
最后,say除非你定义一个方法,否则Ruby中没有方法.通常你会打电话打印一些东西puts.
所以最终的代码如下:
if step =~ /apples|banana|cheese/
puts "yay"
end
Run Code Online (Sandbox Code Playgroud)