No history yet

Introduction to Ruby

The Language of Rails

Before you can build with Rails, you need to understand the language it's built on: Ruby. Ruby is a dynamic, open-source programming language with a focus on simplicity and productivity. Its creator, Yukihiro Matsumoto, designed it to be natural to read and easy to write. Many developers find that Ruby code feels almost like reading plain English, which makes it a great language for beginners.

The core philosophy of Ruby is to make programmers happy. It prioritizes human-friendly syntax over what might be easiest for a computer to understand. This design choice is a big reason why Rails is known for its speed of development.

In Ruby, everything is an object. From a simple number to a piece of text, every value has built-in abilities, or methods, that you can use.

Basic Building Blocks

Let's start with the basics. In Ruby, you store information in variables. A variable is just a name that points to a value. Naming in Ruby follows a simple convention: use snake_case, where words are lowercase and separated by underscores.

user_name = "Alex"
post_count = 42
is_published = true

In that example, we see three of Ruby's fundamental data types:

  • Strings: Plain text, wrapped in double quotes. You can embed variables directly inside strings using a technique called interpolation, like "Welcome, #{user_name}!".
  • Numbers: Integers (like 42) and floating-point numbers (like 98.6).
  • Booleans: Can only be true or false. They are essential for making decisions in your code.

There's one more special value you'll see often: nil. It represents the absence of a value, like an empty box. It's Ruby's version of null.

To hold collections of data, Ruby provides two main structures: Arrays and Hashes.

Arrays are ordered lists of items. You create them with square brackets [].

# An array of strings
tags = ["ruby", "rails", "webdev"]

# Access the first item (indexing starts at 0)
puts tags[0] #=> "ruby"

Hashes are collections of key-value pairs, like a dictionary. You create them with curly braces {}. Each value is associated with a unique key.

# A hash representing a user
user = {
  "name" => "Alex",
  "posts" => 42
}

# Access the value for the "name" key
puts user["name"] #=> "Alex"

Making Decisions and Repeating Tasks

Code isn't just about storing data; it's about doing things with it. Control flow mechanisms let you direct the path your program takes.

The most common way to make a decision is with an if/elsif/else statement. It checks a condition and runs a block of code only if that condition is true.

posts = 1

if posts == 0
  puts "You have no posts."
elsif posts == 1
  puts "You have one post!"
else
  puts "You have many posts."
end

Repetition is handled with loops and iterators. While you can use a while loop to repeat a task as long as a condition is true, Rubyists often prefer using iterators like each. The each method can be called on an array or hash to run a block of code for every single element.

tags = ["ruby", "rails", "webdev"]

tags.each do |tag|
  puts "Tag: #{tag}"
end

This code iterates through the tags array. In each pass, the variable tag holds the current element, which we then print.

Organizing Code with Classes

As your programs grow, you need a way to keep them organized. In Ruby, this is done with classes. A class is a blueprint for creating objects. Think of String as a class; every piece of text you create, like "hello", is an object, or an instance, of that class.

You can define your own blueprints. Let's create a simple User class. By convention, class names use CamelCase.

class User
  # The initialize method runs when a new object is created
  def initialize(name, email)
    @name = name
    @email = email
  end

  # A method to say hello
  def say_hello
    puts "Hi, my name is #{@name}."
  end
end

# Create a new instance of the User class
first_user = User.new("Alice", "alice@example.com")

# Call a method on our new object
first_user.say_hello() #=> "Hi, my name is Alice."

Here, User is the blueprint. initialize and say_hello are methods, which are functions that belong to the class. The variables starting with @ are instance variables; they belong to a specific object and hold its state, like the user's name.

first_user is an object created from our User blueprint. It has its own name and email, and we can call its say_hello method to perform an action.

Sometimes things go wrong. A user might enter bad data, or a file you need might be missing. Ruby lets you handle these situations gracefully with begin and rescue.

begin
  # Code that might cause an error
  result = 10 / 0
rescue ZeroDivisionError
  # Code that runs if that specific error happens
  puts "Oops, you can't divide by zero!"
end

This begin/rescue block attempts to run the risky code. If a ZeroDivisionError occurs, the program doesn't crash. Instead, it jumps to the rescue block and runs that code. This is how you build robust applications that can handle unexpected problems.

This is just a quick tour of Ruby, but it covers the core concepts you'll need to start working with Rails. You've seen how to store data, control your program's flow, and organize your code into reusable objects.