String or string

I am doing something where I do
If “force” || “spells”
Puts “blah”

When I use it it gives a warning about comparing strings, what’s
happening and how do I fix it?

Scratch.mit.edu. Go there!

-gbear605

It doesn’t seem to mind if those are pre-assigned …

ruby-1.9.2-p0 > if “force” || “spells”
ruby-1.9.2-p0 ?> puts “blah”
ruby-1.9.2-p0 ?> end
(irb):3: warning: string literal in condition
(irb):3: warning: string literal in condition
blah
=> nil
ruby-1.9.2-p0 > f = “force”
=> “force”
ruby-1.9.2-p0 > s = “spells”
=> “spells”
ruby-1.9.2-p0 > if f || s
ruby-1.9.2-p0 ?> puts “blah”
ruby-1.9.2-p0 ?> end
blah
=> nil

On Mon, Dec 13, 2010 at 4:53 PM, Garrison Taylor
[email protected]wrote:

-gbear605

|| is a boolean method meaning “or”. It is concerned with the truthiness and
falsiness of its parameters. The set of falsy objects is { false , nil
},
everything else is truthy. That means that strings are truthy, so when
you
say “force” || “spells” it looks at “force”, sees it isn’t false and it
isn’t nil, and so is considered true. Every time.

So “force” || “spells” will always return “force”, a truthy value, to
the if
statement. Thus the if statement will always execute.

if “force” || “spells”
puts “blah”
end

is the same as

if “force”
puts “blah”
end

is the same as

if true
puts “blah”
end

is the same as

puts “blah”

That is probably not what you wanted, so it warns you of the issue.

When I typed it I wasn’t looking at it, it was actually

u2 = gets.chomp
If u2 != “force” || “spells”
Puts “blah”

Scratch.mit.edu. Go there!

-gbear605

I want it to puts blah if u2 isn’t force or spells.

Scratch.mit.edu. Go there!

-gbear605

Same problem, though. That’s the same thing as

if (u2 != "...") || true

Which, of course, is the same thing as “if true”.

Did you mean:

if u2 != “force” && u2 != “spells”

…perhaps?

On Mon, Dec 13, 2010 at 3:27 PM, Garrison Taylor

ruby-1.9.2-p0 > u2 = “foo”
=> “foo”
ruby-1.9.2-p0 > puts “blah” unless [“force”, “spells”].include?(u2)
blah
=> nil
ruby-1.9.2-p0 > u2 = “force”
=> “force”
ruby-1.9.2-p0 > puts “blah” unless [“force”, “spells”].include?(u2)
=> nil
ruby-1.9.2-p0 > u2 = “spells”
=> “spells”
ruby-1.9.2-p0 > puts “blah” unless [“force”, “spells”].include?(u2)
=> nil

On Tue, Dec 14, 2010 at 3:03 AM, Sam D. [email protected]
wrote:

=> “spells”
ruby-1.9.2-p0 > puts “blah” unless [“force”, “spells”].include?(u2)
=> nil

%w can be nicely used here:

Ruby version 1.9.1
irb(main):001:0> %w{foo force spells}.each do |s|
irb(main):002:1* printf “Testing %p\n”, s
irb(main):003:1> puts ‘blah1’ unless %w{force spells}.include? s
irb(main):004:1> puts ‘blah2’ unless s == “force” || s == “spells”
irb(main):005:1> puts ‘blah3’ unless /\A(?:force|spells)\z/ =~ s
irb(main):006:1> end
Testing “foo”
blah1
blah2
blah3
Testing “force”
Testing “spells”
=> [“foo”, “force”, “spells”]
irb(main):007:0>

Kind regards

robert