Introduction

Ruby is an object-oriented programming language, designed to make programmers happy. It has a lot of syntactic sugar that makes Ruby easy to read and fun to learn! In my opinion, Ruby is a great first language for baby code witches!

I'm no technical writer (I'll leave that to my husband, @docswarlock), but let me give you a quick rundown of some Ruby basics.

Comments

There are a couple ways to comment your code in Ruby.

  1. Single-Line:
    # A single-line comment begins with a hashtag.
  2. Multi-Line:
    # A multi-line comment can begin with a hashtag.
    # Each following line
    # also begins with a hashtag.
  3. Block Comment:
    =begin
      Multi-line comments
      can also be nested between =begin and =end.
      This style is known as "block commenting."
    =end

Add comments to explain your code to other readers (including your future self. It's also helpful to note that commented code will not be executed.

Variables

We use variables to store and retrieve data. Think back to your high school algebra class. Ruby variables work in much the same way.

Ruby variables are declared using the assignment operator, also known as the equal sign (=). The variable name goes to the left, and the value is placed on the right.

# the variable, x, equals the value, 1234.
x = 1234

If you need to declare a constant, simply begin your variable name with a capital letter. It is common convention to use all caps for constants.

Constant = "I'm a constant."
BETTERCONSTANT = "I'm a constant that follows conventions."

Methods

Ruby methods, similar to functions in other languages, let you reuse chunks of code. Once you define a method, you can call it in other areas of your program!

To define a method, use the keyword  def , followed by the method's name. It is good practice to name your method in a way that describes its purpose. Close the method definition with the keyword  end .

def say_hello
  puts "Hello World"
end

To invoke a method, simply say the method's name.

# Let's invoke our previous method.
say_hello
=> "Hello World"

Arrays and Hashes

Two common data structures in Ruby are arrays and hashes. Both...

Let's look at an array:

# An array is surrounded by square brackets.
# Each element is separated by a comma.
[ "This", "is", "an", "array", 1, true, false ]

Let's look at a hash:

# An array is surrounded by curly brackets.
# Data is stored in key: value pairs.
# These pairs are separated by commas.
{
  key: value,
  key_with_array_value: ["another", "array"],
  yet_another_key: 12345,
  key_with_boolean: false
}