Ruby: gets, gets.chomp


gets basically gets user input from stdin and returns a string which is passed to chomp

chomp returns a new String with the given record separator removed from the end of str (if present).

Lets say your program is

puts "Your Name: "
name = gets.chomp
puts "Hi, " + name + "!"

This is the output when you type in the name

Your Name: 
Hi, Jason!

Then the sequence of events is:

  1. Prints “Your Name: ” to the screen with the newline.
  2. Gets the input from the user
  3. Removes the last character since no seperator is specified.
  4. Assigns it to name
  5. Prints the greeting
"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"
Stackoverflow Solutions

Just started! Have not answered any questions.