Interpreting Ruby
After creating my first website on Ruby on Rails, a question that kept on popping up in my head whenever I was analyzing and reviewing code was…
What is happening whenever we run our code?
How do computers know how to interpret and give us the correct results, just from our input? This question plagued me all weekend, so I researched it and wanted to share what I found out.
Preface:
We can break programming languages into two different categories based on how their code is read and used: high-level languages and low-level languages. High-level languages that we know are Python, Ruby, Java, etc.… These languages are the popular languages that are used to create software and scripts. Low-level languages are closer to the hardware level. This means that this code is more straightforward for the hardware to understand what is being asked.
We need to understand this concept because this is how compilers/interpreters work. They convert higher-level languages into lower-level languages, so the hardware in your computer can understand what you want it to do.
How does our language interpreter work and read our code?
Some common interpreted languages that are used are Ruby, Python, Perl, and PHP. For our example, we will be looking at a simple line of Ruby code.
That line itself is written in correct ruby syntax, so that our interpreter can understand. When we write code without “speaking” the interpreter’s language, the interpreter will throw out errors, not knowing what you asked it to do.
Now how do we get this line of code to show up on our terminal?
For our program to even run properly, we have to have installed an interpreter to break down the code into a lower-level language. For our purposes, the Ruby Interpreter that is we install to run ruby code is called ‘YARV’ (Yet Another Ruby VM).
When we run the line ‘ruby test.rb’ in our terminal, we are telling our interpreter, ‘YARV’ to run the ruby file, and give us a result from it.
So line by line, the interpreter reads the code, checking to see if there are any errors. When the program is read, it then converts the language into a lower-level language for our virtual machine to read. (This step is what sets ‘Interpreted languages apart from compiled languages’).
The virtual machine also acts as an emulation of a computer and executes the lower-level instructions from ‘YARV’ to return the results we see on the terminal.
=> “Hello, World!”
That completes the cycle of how Ruby gets interpreted. Some other nuances I learned from using Interpreted languages were:
Pros and Cons of Using Interpreted Languages
- Slower runtimes
- Easily transferable across OS systems
- Can execute single lines of code without compiling
- Debugging is easier