Ruby, a dynamic and object-oriented programming language, has charmed developers with its elegant syntax and emphasis on simplicity. Whether you’re a novice coder or an experienced developer exploring new languages, Ruby’s readability and versatility make it an inviting choice. Let’s embark on a journey into the basics of Ruby programming with this Ruby 101 guide.
1. Getting Started: Hello, Ruby!
The hallmark of any programming language introduction is the classic “Hello, World!” program. In Ruby, it’s delightfully simple:
puts "Hello, Ruby!"
This single line demonstrates Ruby’s readability. The puts
method outputs text to the console, and "Hello, Ruby!"
is a string.
2. Variables and Data Types
In Ruby, variables are dynamically typed, meaning you don’t have to explicitly declare their type. Here’s how you declare and use variables:
name = "Alice"
age = 30
is_student = true
Ruby supports common data types like strings, integers, and booleans.
3. Control Flow: Making Decisions
Ruby provides standard control flow structures. For example, the if
statement:
if age < 18
puts "Minor"
else
puts "Adult"
end
4. Loops: Repeating Actions
Use loops to repeat actions. The while
loop is straightforward:
counter = 0
while counter < 5
puts "Iteration #{counter}"
counter += 1
end
5. Arrays: Collections of Data
Arrays hold collections of items:
fruits = ["apple", "banana", "orange"]
puts fruits[1] # Outputs "banana"
6. Hashes: Key-Value Pairs
Hashes store data as key-value pairs:
person = {
"name" => "Bob",
"age" => 25,
"is_student" => false
}
puts person["name"] # Outputs "Bob"
7. Methods: Modular Code
Define methods to organize your code:
def greet(name)
puts "Hello, #{name}!"
end
greet("Eve") # Outputs "Hello, Eve!"
8. Classes and Objects
Ruby is object-oriented, and classes play a central role:
class Dog
def bark
puts "Woof!"
end
end
my_dog = Dog.new
my_dog.bark # Outputs "Woof!"
9. Modules: Reusable Code Units
Modules allow you to group related methods:
module MathOperations
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
end
class Calculator
include MathOperations
end
calc = Calculator.new
puts calc.add(5, 3) # Outputs 8
10. Ruby on Rails: Web Development Framework
Ruby shines in web development, thanks to the Ruby on Rails framework. While a deep dive into Rails goes beyond Ruby 101, its elegance and convention-over-configuration philosophy deserve a mention.
# Ruby on Rails example
class WelcomeController < ApplicationController
def index
@message = "Welcome to Ruby on Rails!"
end
end
This brief Ruby 101 guide merely scratches the surface. As you explore further, you’ll encounter metaprogramming, gems, and a vibrant community that values collaboration and “Matz is nice, so we are nice” (Matz being Yukihiro Matsumoto, Ruby’s creator). Happy coding with Ruby!