Ack
Ack

Reputation: 293

Rails: can I pass multiple values into the include method?

So

shout = "gabba gabba hey"

of course does

shout.include?("gabba")
=> true

shout.include?("nothing")
=> false

Also this works

shout.include?("gabba"||"nothing")
=> true 

However this doesn't

shout.include?("nothing"||"gabba")
=> false

I'm confused. Doesn't this operator work in an include at all, does it stop after evaluating the first value no matter if it returns true or false, or am I just missing something essential? Of course I could use this far longer code

shout.include?("nothing") or shout.include?("gabba")
=> true

but I'd rather have it short and concise.

Upvotes: 0

Views: 700

Answers (2)

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

You should use regexp instead:

!! (shout =~ /(gabba|nothing)/)

/(gabba|nothing)/ is a regular expression matching 'gabba' or 'nothing'

=~ returns the position of the regular expression in your string, if found

!! makes sure the result of the operation is true or false

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

Basically, you can't.

What you tried:

shout.include?('gabba' || 'nothing')

is equivalent to

shout.include?('gabba')

because

'gabba' || 'nothing'
# => 'gabba'

and this is how || operator works in Ruby. It returns first operand unless it's false or nil. Otherwise, it returns second operand. Since your first operand is 'gabba' string, it's being returned.

Upvotes: 1

Related Questions