Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is this a valid ruby syntax?

Tags:

ruby

if step.include? "apples" or "banana" or "cheese"
say "yay"
end
like image 465
gpwu Avatar asked Sep 11 '26 10:09

gpwu


1 Answers

Several issues with your code.

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

This expression evaluates to:

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

Because Ruby treats all values other than false and nil as true, this expression will always be true. (In this case, the value "banana" will short-circuit the expression and cause it to evaluate as true, even if the value of step does not contain any of these three.)

Your intent was:

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

However, this is inefficient. Also it uses or instead of ||, which has a different operator precedence, and usually shouldn't be used in if conditionals.

Normal or usage:

do_something or raise "Something went wrong."

A better way of writing this would have been:

step =~ /apples|banana|cheese/

This uses a regular expression, which you're going to use a lot in Ruby.

And finally, there is no say method in Ruby unless you define one. Normally you would print something by calling puts.

So the final code looks like:

if step =~ /apples|banana|cheese/
  puts "yay"
end
like image 169
Bob Aman Avatar answered Sep 13 '26 07:09

Bob Aman