Ruby Syntax
Ruby syntax is clean and succinct. It reads like English, leaving off the unnecessary syntactic nonsense commonly found in ancient programming languages.
Here is how to print "Hello, World" to the screen in Java:
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
Here is the equivalent "Hello, World" program in Ruby:
print "Hello, World"
# prints "Hello World" to the terminal window.
One language was written for computers, the other for programmer happiness. Can you determine which is which?.
Comments
Notice how we create comments in both examples. Comments are ignored by the computer. They are intended to provide information to the developer or other developers looking at the code. Great code is self explanatory. As such, advanced developers will often advocate for few comments. However, as a beginner, it's better to over-comment than to under-comment. This remains true while you are learning any language. Use comments purposefully, wherever you feel the need. In Ruby, comments begin with #
and go until the end of the line. There are also multi-line comments. Check out the irb session below:
print "Hello, friend"
# print outputs text to the screen. By the way, this is a comment
puts "Hi"
=begin
this is a multi line comment
it spans multiple lines
this type of comment is less popular
but it is good to know it exists
=end
print "no more comments"
# ---> Hello, friend nil
# ---> Hi
# ---> nil
# ---> no more comments nil
Ruby always returns the result of execution. Printing text to the screen has no result, ergo, "nil" is printed to the screen. As you can see, the difference between print and puts is the newline character. Print does not include a newline character, while puts does. Any line starting with a hash sign ( # ) is ignored. All lines between "=begin" and "=end" are ignored as a multi-line comment. Most modern text editors(Atom, Brackets, Sublime, VS Code) allow you to comment/uncomment lines with a keyboard shortcut (cmd + /). This allows users to quickly and easily comment or uncomment one or many lines. For this reason, it's generally easier to use multiple single line comments than a multi-line comment.
Top to Bottom
The ruby interpreter reads your code from top to bottom. It is intuitive enough to know that a newline indicates the end of a line. There is no need to use a line terminator, such as a semicolon. You can still use a semicolon to terminate a line if you wish, the interpreter will continue to read your code.
>> puts "hi"; puts "friend"
hi
friend
nil
Ruby is rather forgiving with respect to its syntax. As you already know, semicolons are not required. The end of a line terminates that line. Another forgiving feature is that Ruby ignores extra spaces. In some languages, specific indentation is required. For example, if you do not properly indent your Python script, the code will not run.
>>> print("hi")
File "<stdin>", line 1
print("hi")
^
IndentationError: unexpected indent
Here i accidentally pressed the space bar before the keyword "print". This single space causes the entire application to come to a grinding halt. In Ruby, indentation is optional. Your code will run with or without indentation. It is a best practice to indent two spaces for each level that needs indenting. You should follow this practice. If you happen to make a mistake and forget to indent some lines, Ruby will still run your program (though the Ruby community may scowl and be less forgiving).
A Friendly Face
Ruby is the most approachable programming language. It reads like English and isn't nearly as restrictive as other languages. Programmers can focus on their programs rather than arbitrary, pointless rules. I'm not saying that all boundaries or restrictions implemented by a language are a bad thing. However, having rules simply for the sake of having rules feels very high school. It's more of a hindrance than anything else. Let's exit the Python interpreter.
>>> quit
Use quit() or Ctrl-D (i.e. EOF) to exit
Python knows that I want to quit the program. It has correctly ascertained my intentions but refuses to acquiesce. Instead, like an annoying know-it-all younger sibling or coworker, it gently lets me know that I'm wrong and corrects me. I often wonder if "programmer happiness" was a cornerstone of Python.
Escape Characters
The backslash ( '\' ) character is called an "escape" character. It allows the character that follows it to escape ruby's interpretation. Let's take a look:
>> puts 'I\'m 6\'0" tall'
I'm 6'0" tall
nil
If our string is encased in single quotes ( ' ) we can't use contractions without getting an error. The word "I'm" will cause the first error, as ruby interprets the apostrophe as the end of the string. The apostrophe representing "feet" in 6'0" will also cause an error. To print the string, we need to escape both apostrophes with the backslash character. If we wanted we could easily encase our string in double quotes:
>> puts "I'm 6'0\" tall"
I'm 6'0" tall
nil
By using double quotes ( " ) the contraction "I'm" won't cause an error. The same is true for the apostrophe representing "feet". However, we need to escape the double quotes that represent "inches" or we will get an error. Once again, the backslash character let's us do this. We can also use the backslash character to include a backslash in our string. In this case, we would need to escape the backslash with a backslash \\
. There are a number of different special characters that can be created using the backslash escape. Here are the most common:
Escape Sequence | Result |
---|---|
\t | creates a horizontal tab |
\n | creates a new line |
\b | creates a backspace |
\r | creates a carriage return |
\ | creates a backslash |