alexmac05
asked on
ruby script, how to read in a string and compare it to a string
This is a very simple question. But, i'm very new to ruby.
I have a script. rubyScript.rb. running it on the command line.
input = ''
while input != '5' do
if input == '1'
puts '1'
end
input = gets
end
However, when I run this and enter 1, the comparison is still false. I tried '1' and 1.
cheers,
alex
I have a script. rubyScript.rb. running it on the command line.
input = ''
while input != '5' do
if input == '1'
puts '1'
end
input = gets
end
However, when I run this and enter 1, the comparison is still false. I tried '1' and 1.
cheers,
alex
I believe gets is returning the value including the newline. Your comparison ends up being:
which is not true. Try ruby's equivalent chomp operator. I'll look to see if I can find it.
if '1\n' == '1'
which is not true. Try ruby's equivalent chomp operator. I'll look to see if I can find it.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for help, however, sadly, it doesn't like any of these solutions either.
tried
"1\n"
"1"
'1'
and i tried adding
input = chomp(input)
script:
input = ''
while input != '5' do
if input == '1'
puts '1'
end
input = gets
input = chomp(input)
end
tried
"1\n"
"1"
'1'
and i tried adding
input = chomp(input)
script:
input = ''
while input != '5' do
if input == '1'
puts '1'
end
input = gets
input = chomp(input)
end
ASKER
this doesn't work either
input = ''
while input != '5' do
if input == '1'
puts '1'
end
input = gets.chomp
end
input = ''
while input != '5' do
if input == '1'
puts '1'
end
input = gets.chomp
end
ASKER
wait, that worked!
sweet
sweet
ASKER
Thanks! helped me a lot.
cheers,
alex
cheers,
alex
This works:
input = ''
while (input = gets.chomp.strip) != '5' do
puts "input: " + input
if input == '1'
puts 'found 1'
end
end
ASKER
Thanks JESii. i had already awarded teh points, but i thank you for the help also!
if input == "1" ...