RbRuby · Lesson 2 of 11

Variables & Types

Ruby is dynamically typed with a twist: everything is an object. Not almost everything — everything. Even nil, true, and integers are objects with methods.

Variables in Ruby need no type declaration. Ruby uses naming conventions to convey scope: lowercase/snake_case for local variables, @variable for instance variables, @@variable for class variables, CONSTANT for constants, and $global for global variables (which you should avoid).

Ruby
# Local variables
name = "Alice"
age  = 30
pi   = 3.14159

# Strings
greeting = "Hello, #{name}!"   # string interpolation with #{}
multiline = <<~TEXT
  This is a
  heredoc string.
TEXT

# Symbols — immutable, memory-efficient strings used as identifiers
status  = :active
action  = :delete
puts status.class   # Symbol
puts status == :active   # true

# nil — Ruby's null
result = nil
puts result.nil?    # true
puts result.class   # NilClass

# Type checks
puts 42.is_a?(Integer)   # true
puts "hi".is_a?(String)  # true
puts 3.14.class           # Float
Ruby
# Type conversion
puts "42".to_i      # 42   (string to integer)
puts "3.14".to_f    # 3.14 (string to float)
puts 42.to_s        # "42" (integer to string)
puts 42.to_f        # 42.0 (integer to float)
puts nil.to_s       # ""   (nil to string — empty)
puts nil.to_a       # []   (nil to array — empty)
puts nil.to_i       # 0    (nil to integer — zero)

# Multiple assignment
a, b, c = 1, 2, 3
first, *rest = [10, 20, 30, 40]
puts first  # 10
puts rest   # [20, 30, 40]

# Swap
a, b = b, a
✦ Tip
Symbols vs Strings: use symbols for identifiers and hash keys (:name, :id, :status), strings for text that will be displayed or manipulated. Symbols are faster for comparison because Ruby stores only one copy of each symbol in memory.