It’s finally time to start coding.
1
|
|
That’s it! Save it as hello_world.rb, exit, and now we can run the file. Note that # is the comment delimiter in Ruby and Shell so I will be using that to give you an idea of the expected result of the line preceding it.
1 2 |
|
Like shell scripts, you can also run them as executables. Create another file:
1 2 |
|
And give it executable permission, and run it.
1 2 |
|
Hashbangs will be explained at the end of this post for those curious
Interactive Ruby Shell
irb
is a tool that provides an interface to Ruby. It’s a great feature, especially for developers new to Ruby because it allows one to interact with Ruby for instant feedback, and build up to a complex script line by line. Code behaves exactly the same way in irb as it would in the method described above. So open up irb
and write Hello World again….puts "Hello World"
You’ll notice that after printing Hello World, it also says => nil; this is the ‘null’ value in Ruby. It’s the value that is returned by the function, and in this case, the value returned by puts
.
If you want to import files that you’ve written, there are two ways to do so. A file that is imported in irb is executed just as it would if it had been imported through normal code, and it is the same as if it had been copy and pasted into irb. The following demonstrates the two major difference between the two options so try this out in irb. Whereas require
is your standard ‘import this library’, load
is more like ‘run this bit of code’.
The first is subtle, but important. The argument to load
is a path to the file. A file you load
can be anywhere on the system, it accepts both relative and absolute paths. The argument to require
is just the name of the file, and it will look for that file only in Ruby’s PATH. Since 1.9.2 however, your working directory is no longer included in it.
1 2 3 4 5 6 7 8 9 |
|
To fix this, we start irb with irb -I .
1 2 3 4 5 6 7 8 9 10 |
|
Let’s try again.
1 2 3 4 5 6 |
|
1 2 3 4 5 |
|
The other difference is that require
will not import a file more than once.
Hashbangs
You might have come across this in COMP2041. This is the line at the top of scripts that tells your shell what to execute it with – your shell will simply interpret it as a shell script without it.
1 2 3 |
|
/usr/bin/env
The characters following the exclamation mark is the path of the executable that you want to run the script with.
Since you now have several different versions of Ruby installed, it’s best to make the script run with the version that you intend to. rbenv controls the Ruby version in your environment, so that’s the best one to use! By /usr/bin/env ruby
, the script will be run with the same ruby as typing ruby in the command line. To demonstrate, create the 2 files below, and then enter the following commands (make note of the versions):
1 2 |
|
1 2 |
|
1 2 3 4 5 6 7 8 9 10 |
|