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.
- # p005methods.rb
- # gets and chomp
- puts "In which city do you stay?"
- STDOUT.flush
- city = gets.chomp
- puts "The city is " + 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. 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 getsreturns 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.