Ruby Syntax Reference For Beginners

Learning Ruby can be overwhelming with all the bits & pieces you have to remember.

That’s why I put together this syntax reference for you!

It will help refresh your memory & quickly review what you need to know to write Ruby programs.

Have fun!

Strings

A string is a sequence of characters inside two quotation marks (""). Used to represent text & data.

Example:

"I like chocolate"

Another option is to use single quotation marks ('').

'Ruby is awesome'

Important methods:

  • size
  • empty?
  • include?
  • gsub
  • split

More methods:

https://www.rubyguides.com/2018/01/ruby-string-methods/

Hashes

A hash ({}) is a key-value pair (a => b) data structure. Used as a dictionary. You can access hash elements by their keys. Keys are unique.

Example:

# Create
h = { a: 1, b: 2, c: 3 }

# Access
h[:a]

# Set
h[:test] = 10

With string keys:

h = { "a" => 1, "b" => 2, "c" => 3 }

Important methods:

  • key?
  • fetch
  • new (for default values)
  • merge

More methods:

http://ruby-doc.org/core-2.6.4/Hash.html

Symbol

A static string used for identification, one common example is hash keys. They always start with a colon (:bacon). Symbols are never used for their content (the individual characters).

When used inside hash brackets ({}) the side of the colon is reversed.

Example:

{ abc: 1 }

This is the symbol :abc.

Learn more:

https://www.rubyguides.com/2018/02/ruby-symbols/

Nil

A singleton class (only one object allowed) that represents a default or “not found” kind of value.

Evaluates to “false” in a conditional context.

Learn more:

Array

An object used to represent a list of objects. An array can contain any kind of object (a = [1, "abc", []]), including other arrays.

You access array elements with their index (a[0]) & nested arrays with a[0][0].

Example:

a = []

a << 10
a << 20
a << 30

a
# [10, 20, 30]

Important methods:

  • size
  • empty?
  • push / pop
  • join
  • flatten

More methods:

http://ruby-doc.org/core-2.6.4/Array.html

Enumerable

A Ruby module used to iterate over the elements of any class that implements the each method, like Array, Range & Hash.

Important methods:

  • map
  • select
  • inject

More:

A Basic Guide to The Ruby Enumerable Module (+ my favorite method)

File

A class that helps you work with files in Ruby. Anything from reading them, writing to them or even getting info about them, like the file size.

Example:

File.read("/tmp/test.txt")

Important methods:

  • read
  • write

More:

https://www.rubyguides.com/2015/05/working-with-files-ruby/

Regular Expression

If you're looking to find patterns, substrings, or something specific inside a string, then a regular expression may be what you're looking for.

They can be used to validate email addresses & phone numbers. Or to extract information from text.

Example:

"aaaa1".match?(/[0-9]/)
# true

"".match?(/[0-9]/)
# false

Learn more:

https://www.rubyguides.com/2015/06/ruby-regex/

Ruby Gems & Bundler

Ruby gems are packages you can download to use in your Ruby programs.

These packages give you new functions.

For example, in Rails you can easily add authentication with the Devise gem, or pagination with the Kaminari gem.

Learn more:

https://www.rubyguides.com/2018/09/ruby-gems-gemfiles-bundler/

Classes & Object-Oriented Programming

Ruby is an Object-Oriented Programming language. We think of everything as an object. Objects are created from their blueprints, classes.

Objects can know things & do things. You tell objects to do things with methods.

Important methods:

  • class
  • include / extend

Learn more:

Types Of Variables

A variable is a label for an object that we can use to access that object. The process of associating a variable with an object is called "variable assignment".

Example:

a = 1

We use different kinds of variables in Ruby.

Here's a list:

  • Local variables (something)
  • Instance variables (@something)
  • Constants (Something / SOMETHING)
  • Global variables ($something)

The main difference is from what locations you can access them.

%w, %i, %q, %r, %x

There is a way to create objects with a special kind of syntax, the percentage symbol.

Examples:

array_of_strings = %w(apple orange coconut)
array_of_symbols = %i(a b c)

string = %q(things)

regular_expression = %r([0-9])

Remember that the percentage symbol (%) is also used as the modulo mathematical operator.

Use of Parenthesis

Parenthesis & semicolons are not required in Ruby, but they can be used.

Some basic rules:

  • DON'T USE parenthesis when defining a method with no arguments => def foo
  • USE parenthesis with method arguments => def foo(a, b, c)
  • USE parenthesis when you want to change the precedence, or priority, of an operation => (a.size + b.size) * 2

Readability is one use for parenthesis, while changing order of operations is another.

Examples

Examples of common Ruby syntax.

Method definition

def backup_database
  # method body
end

More about methods:

Class definition

class Fruit
  # methods
end

More about classes:

Ternary operator

true ? "yes" : "no"

String interpolation

fruit = "orange"

puts "I have an #{fruit}. Would you like a slice of it?"

More about interpolation:

Each with block

[1,2,3].each do |n|
  puts n
end

If / Else

n = 20

if n > 1
  puts "Greater than 1"
else
  puts "Less than 1"
end

Case statement

case 20
when 1..20
  puts "Between 1 & 20"
when 21..40
  puts "Between 21 & 40"
else
  puts "Not within a valid range"
end

Where 1..20 is a Range object.

Summary

You learned the basics of Ruby syntax so you can write Ruby programs! Review these often until it becomes built into your brain.

You may also enjoy this list of common names for syntax elements.

Thanks for reading. 🙂

Leave a Comment: