Your first Ruby script
| Hello file.rb | |
| puts prints | |
| ruby file.rb | |
| Common beginner mistakes |
Hello file.rb
A Ruby script is a plain text file with the rb extension. Open any text editor, type the line below, and save it as hello.rb in your working folder.
puts "Hello, Ruby"
That single line is a complete program. The next section explains what puts does with the string you hand it.
puts prints
puts prints text to the terminal and moves to a new line afterwards, so each call starts on a fresh line. Its sibling print writes without that final newline.
puts "one"
puts "two"
one
two
ruby file.rb
Run the file by passing its name to the ruby command. The interpreter reads hello.rb from top to bottom and prints the result:
Run the script
ruby hello.rb
Hello, Ruby
The terminal prints Hello, Ruby and nothing else. No server and no browser are needed for plain scripts like this one.
Common beginner mistakes
Three mistakes catch almost every beginner. First, typing only the file name runs nothing: the ruby command must come first, as in ruby hello.rb.
Second, a typo such as put instead of puts calls a method that does not exist. Third, an unclosed quote swallows the rest of the line, so close each string on the same line you open it:
puts "Quotes come in pairs: open and close on one line"
Next: Variables
Article author: Arthur Isaev