Let's explore fundamental Ruby concepts through interactive console examples using irb.
Classes and Initialization
class Terminal
attr_accessor :title
def initialize(title = 'Awesome Term')
@title = title
end
def run(command = nil)
puts "Welcome to {title}!"
puts "Running your '{command}' command..." if command
end
end
Key concepts: instance variables (prefixed with @), the initialize method, and require_relative for loading external files.
Getters, Setters, and Attribute Accessors
attr_reader, attr_writer, and attr_accessor are shortcuts to avoid writing boilerplate getter/setter methods.
String Operations
Double quotes support interpolation and escape characters; single quotes are literal.
lang = 'ruby'
puts lang.upcase # => RUBY
puts lang.capitalize # => Ruby
lang.upcase! # Modifies original
puts "Hello! " * 3 # => Hello! Hello! Hello!
Numeric Types
counter = 300
counter += 100 # => 400
pi = 3.14
ten = 10
ten.to_f # => 10.0
Use .to_i and .to_s to convert between types.
Symbols
Symbols share a single memory location, unlike strings:
:hello.object_id # => always the same
"hello".object_id # changes each time
Boolean and Nil
false and nil are always falsy. true, 0, and any object are truthy.
Arrays
arr = ['Ruby', 'on', 'Rails', 7]
arr.join(' ') # => Ruby on Rails 7
arr[0] # => Ruby
arr[-1] # => 7
arr << 1 # Add to end
arr.push(9)
arr.unshift(5) # Add to beginning
arr.pop # Remove last
arr.shift # Remove first
arr[0..3] # Slice
Hashes
h = {
name: 'Alex',
age: 28,
langs: %w(Ruby Elixir Dart)
}
puts h[:name] # => Alex
Note: symbol and string keys are distinct.
Constants
RUBY_VERSION = "3.0.1"
SomeString = "hello"
SomeString = "changes" # Warning issued
Ranges
(1..10).to_a # => [1, 2, 3, ..., 10]
(1..10) === 5 # => true
Control Structures
if version > 2.6
puts "Ok"
elsif version >= 2.3 || version <= 2.5
puts "Legacy"
else
puts "Very old"
end
unless is_eq
puts "enter unless block"
end
case age
when 1..18
puts "<=18"
when 19...31
puts ">18"
else
puts age
end