Syntax
Ruby syntax tour: everything is an object, blocks are the killer feature, and the grammar reads like English when it is in the right shape.
Ruby — syntax tour
EXAMPLE
# ===== Variables (sigils signal scope) =====
local_var = 'hi'
@instance_var = 'state'
@@class_var = 'shared'
$global_var = 'avoid'
CONSTANT = 'caps'
# ===== Strings =====
'single quoted' # literal, no interpolation
"double \#{1 + 1}" # interpolated
'multi
line'
# Heredoc:
text = <<~HEREDOC
indented and stripped
by the squiggly heredoc operator
HEREDOC
# ===== Numbers =====
42
1_000_000 # underscores for readability
3.14
1/2 # 0 (integer division)
1.0/2 # 0.5
# ===== Control flow =====
puts 'big' if age >= 18 # postfix
puts 'small' unless age >= 18 # negated if
if age < 18 then puts 'minor'
elsif age < 65 then puts 'adult'
else puts 'senior'
end
# case (pattern-matching since 3.0):
case order
in { kind: 'pizza', size: }
puts "pizza, \#{size}"
in [first, *rest]
puts "list start \#{first}"
in Integer => n if n > 0
puts "positive int \#{n}"
else
puts 'other'
end
# ===== Iteration =====
[1, 2, 3].each { |x| puts x }
(1..10).each do |x|
puts x
end
# Times:
5.times { |i| puts i }
# Map + filter:
[1, 2, 3, 4].map { |x| x * x }
[1, 2, 3, 4].select(&:even?)
# Reduce:
[1, 2, 3].sum
[1, 2, 3].reduce(0) { |s, x| s + x }
# ===== Methods + blocks =====
def greet(name)
"Hi \#{name}!"
end
def with_db
conn = open_db
yield conn
ensure
conn&.close
end
with_db { |db| db.query('SELECT 1') }
# ===== Classes + modules =====
class User
attr_accessor :name, :email
def initialize(name:, email:)
@name = name; @email = email
end
def to_s = "\#{@name} <\#{@email}>"
end
module Greetable
def greet = "Hi \#{@name}"
end
class Employee < User
include Greetable
end
# ===== Symbols =====
:status # immutable interned symbol
%i[a b c] # array of symbols
# ===== Hashes =====
{ name: 'Alex', age: 30 }
"Alex".tap { |s| puts s.upcase } # tap returns the receiver
# ===== Patterns to internalise =====
# - Default to symbols for hash keys + identifiers
# - Blocks over explicit loops; everything maps + selects
# - .tap and .then for inline debugging + chaining
# - Pattern matching in case/in for structured destructuring
# ===== Pitfalls =====
# - Single quotes do not interpolate; common surprise
# - nil and false are the ONLY falsy values; 0 and '' are truthy
# - method_missing magic that no one can grep for
# - Symbol GC was added; older code worried about leaks
Why it matters
Ruby code reads as much like English as any language. Blocks + iterators + everything-is-an-object + sigils for scope. Lean on map / select / each / tap, use symbols for identifiers, and reach for pattern matching in case/in when shapes get nested.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…