Is this valid ruby syntax?
if step.include? "apples" or "banana" or "cheese"
say "yay"
end
Several problems with your code.
step.include? "apples" or "banana" or "cheese"
This expression evaluates to:
step.include?("apples") or ("banana") or ("cheese")
Since Ruby treats all values other than false
and nil
as true, this expression will always be true. (In this case, the value "banana"
will be a short-circuit expression and cause it to evaluate to true, even if the step value contains none of these three.)
Your intention:
step.include? "apples" or step.include? "banana" or step.include? "cheese"
However, this is ineffective. Also it uses or
instead ||
, which has a different operator precedence and shouldn't normally be used in conditional expressions if
.
Common or
usage:
do_something or raise "Something went wrong."
The best way to write this would be this:
step =~ /apples|banana|cheese/
It uses the regular expression you are going to use in Ruby.
Finally, there is no method in Ruby say
unless you define one. Usually you print something by calling puts
.
So the final code looks like this:
if step =~ /apples|banana|cheese/
puts "yay"
end
The last two expressions appear to Ruby to be true and have nothing to do with the phrase include?
.
Assuming which step
is a string ...
step = "some long string with cheese in the middle"
you could write something like this.
puts "yay" if step.match(/apples|banana|cheese/)
Here, you can call step.include?
for each of the arguments until one of them returns true
:
if ["apples", "banana", "cheese"].any? {|x| step.include? x}
This is definitely not what you think you want. The method include?
takes on a value String
that is not what it creates "apples" or "banana" or "cheese"
. Try this instead:
puts "yay" if ["apples", "banana", "cheese"].include?(step)
But it is not clear from the context which step should be. If it's just one word, then it's okay. If it could be a whole sentence, try joel.neely's answer.
The closest thing to a syntax that will do what you think you want is something like this:
if ["apples", "banana", "cheese"].include?(step)
puts "yay"
end
But one of the other suggestions using regex would be more concise and readable.
Assuming that step
is Array
or Set
or something else that supports the given operator intersection &
, I think the following code is the most idiomatic:
unless (step & ["apples","banana","cheese"]).empty?
puts 'yay'
end
I'll add some parentheses for you:
if (step.include? "apples") or ("banana") or ("cheese")
say "yay"
end
(This is why he always says "yay" - because the expression will always be true.)
Just add one more side ...
If it step
is Array
(as the call seems to suggest include?
), perhaps the code should be:
if (step - %w{apples banana cheese}) != step
puts 'yay'
end