1. Computing

Getting and Printing Strings


Reading with 'gets'

The gets method will read a string from the keyboard and return it. It will pause the program and continue reading characters until the enter key is pressed. This is often accompanied by a print method call to make a sort of prompt. Though this is quite primitive, tools like irb use the Readline library for line editing. Without that, you'll only be able to type and use the backspace key, no line editing will be available.

A common idiom is gets.chomp. When the enter key is pressed, it generates a newline character and this is rarely wanted in the string. In the example below, if I were to enter "Michael" then the string returned by gets would be "Michael\n" with the newline at the end. This is not what's wanted, so the string is "chomped" with the chomp method, which will return any record separators (in this case, the newline) it finds at the end of the string.

print "What is your name? "
name = gets.chomp
puts "Hello #{name}"

But, if you really look at this idiom, it seems a bit strange. Is gets an object? I thought it was a method? It is a method, but when the dot operator follows a method, it will be applied to the object returned by the method, and not the method itself (which would make little sense).

  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Strings
  6. Getting and Printing Strings

©2014 About.com. All rights reserved.