Getting Input


So far we had 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.

In the above example when you run it in SciTE, click on the output window (on the right side of SciTE) and then type the name of your city.

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.

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.