A Ruby Syntax Primer

So you want to get started with Ruby on Rails, but you have no experience with Ruby at all? Or maybe you need a refresher after a few months away from coding anything in Ruby?

This post gives you the Ruby Minimum Viable Syntax so you can get going.

Ruby

Ruby is a dynamic object-oriented programming language (everything's an object in Ruby). It was created by Yukihiro Matsumoto during the mid-90s. It grew in popularity exponentially when Ruby on Rails starting becoming the popular kid on the block for building web applications.

Ruby's emphasis is on productivity and programmer enjoyment. In other words, it focuses on being less a pain in the ass.

Installing Ruby

If you're on a Mac or Linux, chances are good that you already have a version of Ruby installed. It might not be the most recent version however, v2.2.3 at the time of this writing.

To install the latest version, the most common way is to use RVM (Ruby Version Manager).

Here's how to install RVM from the terminal and then Ruby and Rails from it:

$ gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
$ \curl -sSL https://get.rvm.io | bash -s stable --ryby --rails

Running some code

Once you have Ruby installed on your machine, it’s easy to start playing around and running some code with irb (interactive Ruby). Just type irb in your terminal and you’ll get a prompt that’ll look like irb(main):001:0> and you’ll be able to run some Ruby code from there.

A few words on the syntax in general

No semi-colons at the end of each line in Ruby, just start every new expression on its own line. You can continue a long expression on multiple lines using the \ character at the end of the line. Indents are not mandatory, but 2-space indentation is common use for readability and maintainability.

Ruby files have the extension .rb and here’s how to print something on the screen in Ruby:

puts "Hello, Alligator!"

Or, with the print command, which differs from puts in that it doesn’t add a new line in the output:

print "Hello, Alligator!"

Reserved Keywords

Here are the keywords you can't use as identifiers in Ruby:

BEGIN, END, alias, and, begin, break, case, class, def, defined, do, else, elsif, end, ensure, false, for, if, in, module, next, nil, not, or, redo, rescue, retry, return, self, super, then, true, undef, unless, until, when, while, yield

Identifier and Variable Names

Identifiers and variables are case sensitive and can contain letters, decimal digits or _ characters. They must not begin with a digit. Identifiers that begin with a capital letter are constants.

comments

You use # for comments. Most of the time # is used for multiline comments as well:

# This is a comment

# Comment on
# multiple
# lines

Multiline comments can also be created like so:

=begin
Comment on
multiple
lines
=end

Data Types

Strings

Strings are objects too in Ruby and you can do things like:

"Alligator".size

Which will output this:

=> 9

There are tons of useful methods available for strings in Ruby. Here are a few that can come in really handy, most of them are self-explanatory:

capitalize, chars, chomp, chop, chr, count, delete, empty?, end_width?, eql?, include?, index, replace, reverse, slice, strip, swapcase

Notice the methods that end with ? It’s common use in Ruby to end method names with a question mark when they return true or false.

Integers

We won’t go over every Ruby data type here, but integers give another good example that show just how much everything is an object in Ruby. You can for example call methods on integers like this:

666.odd?

This would return false, because 666 is an even number.

Arrays

Like many other languages, arrays in Ruby are indexed collections of objects. Different types of objects can be used in the same array. The index is zero-based, which just mean that the first thing in an array is at position 0. If you’re looking for the 3rd object in an array, you’ll use the index 2.

Here are two valid ways to declare an array:

my_array = ["Something", "very", "boring"]

# And this is equivalent:
my_array = Array.new(["Something", "very", "boring"])

Arrays also have some very useful methods, and here are a few:

any?, collect, compact, concat, count, delete, drop, each, empty?, eql?, first, include?, index, last, length, pop, push, reverse, shift, shuffle, slice, sort, unshift

Hashes

Hashes are like dictionnaries. Instead of all the objects within them being indexed, they are associated with a unique key that can be any type of object:

accused = { "who" => "You", "with_what" => "club" }

It’s common practice to use symbols as hash keys:

accused = { :who => "You", :with_what => "club" }

In cases where you use symbols only as keys, you can use this concise syntax:

accused = { who: "You", with_what: "club" }

Again, hashes have many useful methods, and here are a few of them:

any?, clear, compare_by_identity, default, delete, each, each_key, each_pair, each_value, empty?, eql?, fetch, has_key?, has_value?, include?, invert, keep_if, length, shift, size

Symbols

Symbols in Ruby are a bit of an odd child. They start with a : character and can be seen quite often in Ruby or Rails projects. They are similar to strings, but are immutable. They can’t change throughout the course of a program’s execution once they are first created. That makes them faster to access and process, which in turn makes symbols ideal as keys in a hash for example.

Conditional statements

If…elsif…else

Ruby comes with some interesting ways to structure conditional statements. Here’s the traditional if statement:

kevin = "Pig vomit"
if kevin.length > 10
  puts "Not quite"
elseif kevin.length === 9
  puts "I think we have a winner"
else
  puts "Getting cold"
end

Notice the keyword elsif here, not elseif or else if, elsif! With simple if statements you can structure them on one line like this:

puts "Yes" if kevin.length === 9

Unless statements

You can apply the reverse logic by using unless statements:

letters = ["A", "l", "l"]
unless letters[1] === "l"
  puts "This won't print"
end

In the above example, the body of the condition won’t execute because the condition evaluates to true. unless statements are often more intuitive than using an if not logic, they are closer to natural language.

Here’s another example, using the one-liner syntax:

puts "Ok" unless letters.length > 3

Case statements

Yet another way to structure a conditional statement is whith a case statement. They help in otherwise very complicated if statements:

moon_to_earth = 238900
case
when moon_to_earth < 200000
  puts "Not quite back home"
when moon_to_earth < 250000
  puts "Went too far"
when moon_to_earth === 238900
  puts "Spot on!"
else
  puts "Off the track again"
end

Or you can start the case statement with the variable that you’re evaluating. Notice here how it’s possible to use all kinds of statements to evaluate:

moon_to_earth = 238900
case moon_to_earth
when 1..200000
  puts "Not quite back home"
when String
  puts "We're looking for an integer"
when 238900
  puts "Spot on!"
else
  puts "Off the track again"
end

Work in progress…

✖ Clear

🕵 Search Results

🔎 Searching...