Crystal Methods — Def, Return Types, Named Arguments and Blocks
DodaTech
Updated 2026-06-29
1 min read
In this tutorial, you will learn about Crystal Methods. We cover key concepts, practical examples, and best practices to help you master this topic.
Crystal methods combine Ruby's flexible syntax with static Type Checking. Every method has a known return type, inferred or declared.
Basic Methods
def greet(name : String) : String
"Hello, #{name}!"
end
puts greet("Alice") # => Hello, Alice!
# Without return type (inferred)
def add(a, b)
a + b
end
# Default arguments
def create_url(host, port = 443, path = "/")
"https://#{host}:#{port}#{path}"
end
Blocks and Yield
def twice
yield
yield
end
twice { puts "Hello" }
# Output: Hello (twice)
# With arguments
def each_item(items)
items.each { |item| yield item }
end
each_item([1, 2, 3]) { |x| puts x * 10 }
← Previous
Crystal Control Flow — if, unless, case, while, and until
Next →
Crystal Classes — Inheritance, Abstract Classes, and Method Overrides
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro