Comparison error

J

Jake Alucard

so i'm writing a program for class that tells the user if the person is
20 or under then they get a green and if the person is 21 or over then
tehy get red here's the code and error




age = ageText.to_s

if age <= 20
status = "GREEN"
else
status = "RED"
end






C:/ruby/martinilounge.rb:69:in `<=': comparison of String with 18 failed
from C:/ruby/martinilounge.rb:69
from C:/ruby/martinilounge.rb:98:in `call'
from C:/ruby/martinilounge.rb:98:in `main'
from C:/ruby/martinilounge.rb:98
 
R

Rajinder Yadav

so i'm writing a program for class that tells the user if the person is
20 or under then they get a green and if the person is 21 or over then
tehy get red here's the code and error




age = ageText.to_s

if age<= 20
status = "GREEN"
else
status = "RED"
end






C:/ruby/martinilounge.rb:69:in `<=': comparison of String with 18 failed
from C:/ruby/martinilounge.rb:69
from C:/ruby/martinilounge.rb:98:in `call'
from C:/ruby/martinilounge.rb:98:in `main'
from C:/ruby/martinilounge.rb:98

20 is not a string =), possible you want to do the following

age = ageText.to_i

you can also do

age = Integer(ageText)

the 2nd form will throw an ArgumentError exception if ageText is not a
number, while the 1st form will simply return some integer value, you
can play around with the them in irb:


irb(main):001:0> "$55".to_i
=> 0

irb(main):002:0> "33".to_i
=> 33

irb(main):003:0> "33rr12".to_i
=> 33

irb(main):004:0> nil.to_i
=> 0

irb(main):005:0> "rrr".to_i
=> 0

irb(main):006:0> Integer("12")
=> 12

irb(main):007:0> Integer("$12")
ArgumentError: invalid value for Integer(): "$12"
from (irb):7:in `Integer'
from (irb):7
from /usr/local/bin/irb:12:in `<main>'



--
Kind Regards,
Rajinder Yadav | DevMentor.org | Do Good! ~ Share Freely

GNU/Linux: 2.6.35-22-generic
Kubuntu x86_64 10.10 | KDE 4.5.1
Ruby 1.9.2p0 | Rails 3.0.1
 
R

Rajinder Yadav

Rajinder Yadav wrote in post #955622:

Beware that it also has some other behaviour you might not expect.

=> 32

nice thanks for pointing that out =)
 

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

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top