Running Ruby

Running Ruby#

Ruby is the interpreted language, so there is no need to compile your program before running. Just like in a shell, you can create a script or run the command you want to from the ruby executable command line. We will start with the famous Hello, world program.

One-Liners in Ruby#

To run a command in ruby, use -e command line switch:

ruby -e 'puts "Hello, world."'
Hello, world.

Or send the code to the stdin of ruby executable:

$ echo 'puts "Hello, world."' | ruby
Hello, world.

puts (stands for: put string) is an equivalent to echo in Shell scripting: this is a function which sends the given text string to stdout.

While running one-liner you can pass the command line arguments to your program. In the example below the argument is just one - a text string ‘JanB’, but of course you can have as many arguments as you want.

$ ruby -e 'puts "Hello, " + ARGV.first + "."' JanB
Hello, JanB.

ARGV is an array with all the command line arguments passed to ruby program. When no arguments are given, this array will be empty (but still exists). In our case, ARGV has only one element, text string ‘JanB’. Method first called on the array returns, as you probably guess, the first item of collection. Adding two string one to another using the plus sign concatenates them, for example: ”1” + “2” gives ”12”.

Scripting#

To create a script, prepare a file called hello_world.rb (.rb is well-know extention for Ruby programs, but it is of course not mandatory) with your favourite emacs or vi:

puts "Hello, world."

And you can run it now:

$ ruby hello_world.rb
Hello, world.

Passing the arguments is easy, just the same as in one-liner above. In hello_world.rb, type:

puts "Hello, " + ARGV.first + "."

And run it with argument:

$ ruby hello_world.rb "Jan B"
Hello, Jan B.

Shebang#

Because Ruby executable can read the program from the stdin, it is easy to create standalone executable using shebang similar to shell scripts. For the best flexibility use #!/usr/bin/env ruby, which runs Ruby executable found in your PATH. Or directly specify which Ruby executable you want to use, like #!/usr/local/bin/ruby19.

With the shebang, hello_world.rb should now looks like:

# !/usr/bin/env ruby
puts "Hello, " + ARGV.first + "."

Shebang is the magic characters sequence #! used at the beginning of the Unix shell script to show the program loader which interpreter to run with this script. With shebang, system will run the executable specified after #! and pass the content of the script to it. The shebang itself will not be interpreted, because in the most shells (and in Ruby as well) the line beginning with # is a comment.

Adding executable attribute to the script file with shebang allows you to run the Ruby program like the other scripts or executables:

$ chmod u+x hello_world.rb
$ ./hello_world.rb Stranger
Hello, Stranger.