Lesson 2 of 11
Variables & Types
Learn how , , numbers and symbols work in Ruby. Every value in Ruby is an object with , including nil, true and integers.
Variables in Ruby need no type declaration. Ruby uses naming conventions to convey : lowercase/snake_case for local variables, @variable for variables, @@variable for class variables, CONSTANT for constants, and $global for (which you should avoid).
# 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# 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, aFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.