String or string

G

Garrison Taylor

I am doing something where I do=20
If "force" || "spells"
Puts "blah"



When I use it it gives a warning about comparing strings, what's happening a=
nd how do I fix it?

Scratch.mit.edu. Go there!

-gbear605=
 
G

Garrison Taylor

When I typed it I wasn't looking at it, it was actually=20

u2 =3D gets.chomp
If u2 !=3D "force" || "spells"
Puts "blah"

Scratch.mit.edu. Go there!

-gbear605
 
R

Ross Harvey

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

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

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

Did you mean:

if u2 !=3D "force" && u2 !=3D "spells"

...perhaps?
 
G

Garrison Taylor

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

Scratch.mit.edu. Go there!

-gbear605
 
S

Sam Duncan

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
 
R

Robert Klemme

ruby-1.9.2-p0 > u2 =3D "foo"
=A0=3D> "foo"
ruby-1.9.2-p0 > puts "blah" unless ["force", "spells"].include?(u2)
blah
=A0=3D> nil
ruby-1.9.2-p0 > u2 =3D "force"
=A0=3D> "force"
ruby-1.9.2-p0 > puts "blah" unless ["force", "spells"].include?(u2)
=A0=3D> nil
ruby-1.9.2-p0 > u2 =3D "spells"
=A0=3D> "spells"
ruby-1.9.2-p0 > puts "blah" unless ["force", "spells"].include?(u2)
=A0=3D> 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 =3D=3D "force" || s =3D=3D "spells"
irb(main):005:1> puts 'blah3' unless /\A(?:force|spells)\z/ =3D~ s
irb(main):006:1> end
Testing "foo"
blah1
blah2
blah3
Testing "force"
Testing "spells"
=3D> ["foo", "force", "spells"]
irb(main):007:0>

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,787
Messages
2,569,631
Members
45,338
Latest member
41Pearline46

Latest Threads

Top