Like Progressive Metal? Check out my band on Spotify, please follow us!
Ruby Scripting Scripting Tutorial
Ruby is a great flexible object-oriented and functional programming language that can be used in many situations. In this tutorial, we will focus primarily on it's ability to enhance the Unix/Linux shell environment. Typically in Unix you will create "bash" shell scripts, but you can also create shell scripts using ruby, and it's really simple! You can even name your shell scripts with the .sh extension and run them as you would run any bash shell script. All you need to do this is to modify the very first line of your file like so:
In this tutorial, we will use the extension .rb, just to help us know that the script contians ruby code and not standard unix shell commands.
The first script that we will use will be a simple script that will output the text "Hello Ruby". You can use any file editor, personally, I use vi. Create a file named "hello.rb" and use the following for its contents:
#!/usr/bin/ruby -w # This is my first script. puts "Hello Ruby"
Two things you will notice besides the header which we previously discussed. The second line starting with "#" is a comment. Comments are ignored by the interpreter but are very useful when developing large and complex scripts. Everyone forgets what their original logic or intention was when coding a script and it's much easier to read a comment than it is to try to understand large and complex sections of code.
The next thing you will notice is puts keyword. This will print text to the console, much line the unix "echo" command.
Assuming you are running on unix, before we can run this script, we must first make it executable. To do this we will use the unix chmod command:
chmod u+x hello.rb
Now our script is executable. This command basically tells unix to set the x (executable) flag for the user level access of the file. Now we are able to run the file. If you don't have "." in your unix PATH environment variable, then you will need to proceed the name of the script with "./" to execute it. It is generally considered to be a security risk to put "." in your PATH evironment variable, so we will assume that you don't have it. Now you can execute your script by using the following command:
You will see the text "Hello Ruby" output to the console, congratulations, you have created your first Ruby script! Now you can move on to the next topic where we will discuss using variables in a Ruby script.