I'm getting error like comparison of string with 50 failed
for the below code snippet.Please guide me to resolve
print(' Enter your mark :')
mark = gets()
if(mark < 50)
puts( " You passed")
else
puts(" You just scored #{mark} which is not enough to pass ")
end
···
--
Posted via http://www.ruby-forum.com/.
When you do the mark = get() what you actually get back is a string
and not a number. You cant compare a string to a number so the if(mark
< 50) fails. You need top convert the string into a number. You should
do this
if(mark.to_i < 50)
this will convert the string into an integer (if it can).
···
On 30 December 2011 18:58, sathish babu <sathish.babu@india.com> wrote:
I'm getting error like comparison of string with 50 failed
for the below code snippet.Please guide me to resolve
print(' Enter your mark :')
mark = gets()
if(mark < 50)
puts( " You passed")
else
puts(" You just scored #{mark} which is not enough to pass ")
end
--
Posted via http://www.ruby-forum.com/\.
I'm getting error like comparison of string with 50 failed
That's the problem. In ruby, you can't compare a string with a number (you'll
get an ArgumentError exception). First, you have to convert the string to a
number, usually using String#to_i or String#to_f.
for the below code snippet.Please guide me to resolve
print(' Enter your mark :')
mark = gets()
if(mark < 50)
puts( " You passed")
else
puts(" You just scored #{mark} which is not enough to pass ")
end
Replace
mark = gets()
with
mark = gets().to_i
and it'll work.
I hope this helps
Stefano
···
Il giorno Sat, 31 Dec 2011 03:58:15 +0900 sathish babu <sathish.babu@india.com> ha scritto:
Peter Hickman wrote in post #1038899:
When you do the mark = get() what you actually get back is a string
and not a number. You cant compare a string to a number so the if(mark
< 50) fails. You need top convert the string into a number. You should
do this
if(mark.to_i < 50)
this will convert the string into an integer (if it can).
Thanks a lot Mr.Hickman understood the basic casting.
···
--
Posted via http://www.ruby-forum.com/\.
Stefano Crocco wrote in post #1038900:
Replace
mark = gets()
with
mark = gets().to_i
and it'll work.
I hope this helps
Stefano
Thanks a lot Crocco...! Understood and great explanation
···
--
Posted via http://www.ruby-forum.com/\.