Skip to main content
Ruby

Ruby – getting input from your users

By October 10, 2013No Comments



As we move along in learning ruby we will now look at creating scripts rather than just using the interactive ruby shell, irb. I am using ruby on Linux and these demonstrations are using CentOS 6.4. In other demonstrations I use Ubuntu. Ruby has cross platform support and can be used on Windows, MAC as well as Linux. Both with CentOS and Ubuntu ruby can be found with standard repositories.

It is convention that the name of the file should end in .rb if we are creating ruby scripts. In this tutorial we look at 3 scripts:

  • h1.rb : A simple hello world program that does not gather user input
  • h2.rb : A hello world program that users command line arguments passed into the script to adjust the hello message
  • h3.rb : Where we use an interactive script to prompt for the name whilst the script runs.

h1.rb

#!/usr/bin/ruby
puts "Hello World"

Line 1: The shebang tells Linux which command interpreter to use in executing the script
Line 2: We print the hello world message. Puts adds and additional line feed after the message

h2.rb

Of course having only static text in the script is not always what we require. We can add a little more to the script by allowing the script to read from arguments provided when the script is run. We can use the same array ARGV as in many other languages.

#!/usr/bin/ruby
puts "Hello #{ARGV[0].captitalize}"

This script reads the first argument supplied to the script and prints that along with the hello message. The variable comes from an array ARGV, the index is 0 being the first value in the array. So ARGV[0] represents the first argument to the script. As this is in a quoted string along with the hello message we delimit it from the string using #{ }. In this way we know that this a varilable and not just the text ARGV. In addition we implement the capitalize method to upper case the first character for the ARGV[0] string and convert the rest to lower case. Executing the script as

./h2.rb fred

Will return Hello Fred

h3.rb

In this third script we look at gaining input from the user during script execution rather than at the start of the script

#!/usr/bin/ruby
print “Enter your name…. ”
STDOUT.flush
name = gets.chomp
puts “Hello #{name.capitalize}”

Line 2: Now uses print rather than puts. It is better not to have the extra line feed that puts adds when prompting for data. This way the prompt is on the same line as the user input.
Line 3: Is not strictly necessary but is best practice to flush your output buffers before reading input. (Take a pee before another drink!)
Line 4: We populate th local variable name with the first line of user input. This is provided by gets. The method chomp removes the training line feed from the user input. Notice the streamlining of methods here gets.chomp
Line 5: Is as before but this time we are printing the name variable.