To read from user via console window, use Ruby method gets.
The following code prompts the user for his or her name.
And then displays a greeting: "Hello Fred." Here is the code:
print( 'Enter your name: ' ) name = gets() puts( "Hello #{name}" )
puts function adds a line feed at the end of the printed string, whereas print does not.
gets() reads in a string when the user presses ENTER.
This string is assigned to the variable name.
We have not predeclared this variable, nor have we specified its type.
In Ruby, you can create variables when you need them, and the interpreter "infers" their types.
In the example, I have assigned a string to name so Ruby knows that the type of the name variable must be a string.
Ruby is case sensitive.
A variable called myvar is different from one called myVar.
A variable such as name in the sample project must begin with a lowercase character.
If it begins with an uppercase character, Ruby will treat it as a constant.
The parentheses following gets() are optional, as are the parentheses enclosing the strings after print and puts.