Getting Input


So far we have seen a method like puts that writes to the screen. How does one accept user input? For this gets (get a string) and chomp are useful. The example p005methods.rb below illustrates the same.

STDOUT is a global constant which is the actual standard output stream for the program. flush flushes any buffered data within io to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well). The usage is not mandatory but recommended. Note: STDOUT.sync = true will allow you to have flushed Ruby based IO without repeated .flush calls.

gets accepts a single line of data from the standard input - the keyboard in this case - and assigns the string typed by the user to city. The standard input is a default stream supplied by many operating systems that relates to the standard way to accept input from the user. In our case, the standard input is the keyboard.

chomp is a string method and gets retrieves only strings from your keyboard. You must have realised that gets returns a string and a '\n' character, while chomp removes this '\n'.

IN RAILS: Data comes from many sources. In the typical Rails application, it comes from a database. As a Rails developer, you may find yourself using relatively few of these facilities, because Rails does the data-fetching for you; and your users, when they input from the keyboard, will generally be typing on a Web form.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.com and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.