TL;DR
En resumen: Ruby está diseñado para la felicidad del desarrollador - expresivo, elegante y productivo.
Fortalezas principales:
- Sintaxis hermosa y legible
- Todo es un objeto
- Framework Rails para desarrollo web rápido
- Comunidad vibrante y rico ecosistema de gemas
Philosophy
Ruby sigue el principio de menor sorpresa:
- Optimizado para la felicidad del desarrollador - Matz diseñó Ruby para que sea divertido
- Todo es un objeto - Incluso los números y nil tienen métodos
- Duck typing - Si camina como pato, es un pato
- Convención sobre configuración - Valores predeterminados sensatos, menos boilerplate
Ruby valora la expresividad sobre el rendimiento. Es un lenguaje donde escribes lo que quieres decir.
Quick Start
Install
# macOS
brew install ruby
# Linux - use version manager (recommended)
curl -fsSL https://github.com/rbenv/rbenv-installer/raw/HEAD/bin/rbenv-installer | bash
rbenv install 3.4.8
rbenv global 3.4.8
Verify (latest: 3.4.8)
ruby --version # ruby 3.4.8
First Program
Crea hello.rb:
puts "Hello, World!"
ruby hello.rb
Interactive Ruby (IRB)
irb
>> 2 + 2
=> 4
>> "hello".upcase
=> "HELLO"
Language Essentials
Variables & Types
# Variables (no type declarations)
name = "Alice"
age = 25
price = 19.99
active = true
# Symbols (immutable identifiers)
status = :pending
# Arrays
numbers = [1, 2, 3]
mixed = [1, "two", :three]
# Hashes (dictionaries)
user = { name: "Alice", age: 25 }
user[:name] # "Alice"
Control Flow
# if-else
if age >= 18
puts "Adult"
elsif age >= 13
puts "Teen"
else
puts "Child"
end
# One-liner
puts "Adult" if age >= 18
# unless (opposite of if)
puts "Minor" unless age >= 18
# case (pattern matching)
case status
when :pending
"Waiting"
when :active, :running
"In progress"
else
"Unknown"
end
Iterators & Blocks
# Blocks are everywhere
5.times { puts "Hello" }
# each
[1, 2, 3].each { |n| puts n }
# map
doubled = [1, 2, 3].map { |n| n * 2 } # [2, 4, 6]
# select (filter)
evens = [1, 2, 3, 4].select { |n| n.even? } # [2, 4]
# Multi-line block
numbers.each do |n|
puts n * 2
end
Methods
# Method definition
def greet(name)
"Hello, #{name}!" # Implicit return
end
# Default parameters
def greet(name, greeting = "Hello")
"#{greeting}, #{name}!"
end
# Keyword arguments
def create_user(name:, age:, admin: false)
{ name: name, age: age, admin: admin }
end
create_user(name: "Alice", age: 25)
Classes
class User
attr_accessor :name, :age # Getters and setters
def initialize(name, age)
@name = name # Instance variable
@age = age
end
def adult?
@age >= 18
end
end
user = User.new("Alice", 25)
user.name # "Alice"
user.adult? # true
Gotchas
nil es falsy, pero 0 y "" son truthy
if nil
# won't run
end
if 0
puts "0 is truthy!" # Will print!
end
if ""
puts "empty string is truthy!" # Will print!
end
Symbols vs Strings
# Symbols are immutable and memory-efficient
:name.object_id == :name.object_id # true
# Strings are mutable
"name".object_id == "name".object_id # false
# Use symbols for hash keys
user = { name: "Alice" } # Symbol key
user[:name] # Access with symbol
Retorno implícito
def add(a, b)
a + b # Last expression is returned
end
# Explicit return only when needed
def early_exit(n)
return "negative" if n < 0
n * 2
end
Convenciones de nombres de métodos
# ? for predicates (return boolean)
"hello".empty? # false
[1, 2].include?(1) # true
# ! for dangerous/mutating methods
str = "hello"
str.upcase # Returns "HELLO", str unchanged
str.upcase! # Modifies str in place
When to Choose
Ideal para:
- Aplicaciones web (Ruby on Rails)
- Prototipado rápido
- Scripting y automatización
- Startups que necesitan desarrollo rápido
No ideal para:
- Aplicaciones críticas en rendimiento
- Desarrollo móvil
- Ciencia de datos (usar Python)
Comparación:
| Aspecto | Ruby | Python | JavaScript |
|---|---|---|---|
| Framework web | Rails | Django | Express |
| Sintaxis | Elegante | Limpia | Flexible |
| Velocidad | Lento | Medio | Medio |
| Caso de uso | Web | General | Full-stack |
Next Steps
Ecosystem
Package Management
gem install rails # Install a gem
gem list # List installed gems
bundle init # Create Gemfile
bundle install # Install dependencies
Popular Gems
- Web: Rails, Sinatra, Hanami
- Testing: RSpec, Minitest
- Database: ActiveRecord, Sequel
- Background Jobs: Sidekiq, Resque