Link to home
Start Free TrialLog in
Avatar of alexmac05
alexmac05Flag for United States of America

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



Avatar of HainKurt
HainKurt
Flag of Canada image

try double quotes

if input == "1" ...
Avatar of kaufmed
I believe gets is returning the value including the newline. Your comparison ends up being:

if '1\n' == '1'

Open in new window


which is not true. Try ruby's equivalent chomp operator. I'll look to see if I can find it.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of alexmac05

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

this doesn't work either
input = ''

while input != '5' do
   if input == '1'
      puts '1'
   end

   input = gets.chomp
end

wait, that worked!

sweet
Thanks! helped me a lot.

cheers,
alex
This works:


input = ''

while (input = gets.chomp.strip) != '5' do
  puts "input: " + input
  if input == '1'
     puts 'found 1'
     end
end

Open in new window

Thanks JESii. i had already awarded teh points, but i thank you for the help also!