James Jeffery
James Jeffery

Reputation: 12599

Ruby While Issue

I'm just learning Ruby, and I'm a bit confused at the following:

#!/usr/bin/env ruby

while line = gets
  if line == 'x'
    puts 'You pressed x'
  end
end

It doesn't seem to print anything if x is entered. Am I doing the comparison correctly?

Upvotes: 0

Views: 60

Answers (2)

Leo Correa
Leo Correa

Reputation: 19789

When you type x then press enter you're adding \n and/or \r.

To fix this you have to compare

if line.chomp == 'x'

Your loop should work and print out "You pressed x"

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

gets returns entered text along with the linebreak. Try this:

while line = gets.chomp
  # the rest is the same
end

String#chomp removes such characters (\n, \r, \r\n) from a string.

Upvotes: 5

Related Questions