0

A simple issue, but can't figure out how to solve it, lacking knowledge in Ruby language:

class Game
  def initialize
    get_command
  end
  def get_command
    command = gets
    puts command                # => POSITION
    puts command != "POSITION"  # => true
    if command != "POSITION"
      command = get_command 
    else  
      return true
    end
  end
end

a = Game.new

Whenever I run an application and type POSITION it always gets the true comparing to "POSITION" can anyone explain why?

Thanks

1 Answer 1

2

Because what you're actually getting is "POSITION\n". You can see this in irb:

1.9.3p194 :061 > command = gets
POSITION
 => "POSITION\n"

You should strip the command before doing comparisons:

command = gets.strip

or

command = gets.chomp

This will strip whitespace (including newlines) off of the input.

Sign up to request clarification or add additional context in comments.

1 Comment

Always a good idea to sanitize user input -- especially since the end-of-line character is different on different platforms

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.