Methods and blocks
Define methods with def, keyword arguments, implicit return, blocks with yield, and lambdas.
Runs in Zerethon IDE · Ruby 4.0
Official Ruby documentation ↗
main.rb
def greet(name, greeting: "Hello")
"#{greeting}, #{name}!"
end
def stats(numbers)
[numbers.min, numbers.max, numbers.sum.to_f / numbers.size]
end
def twice
yield 1
yield 2
end
puts greet("Ada")
puts greet("Linus", greeting: "Hi")
low, high, mean = stats([4, 8, 6])
puts "#{low} #{high} #{mean}"
twice { |n| puts "block got #{n}" }
square = ->(x) { x * x }
puts square.call(9), square.(3)
Output
Hello, Ada! Hi, Linus! 4 8 6.0 block got 1 block got 2 81 9
- A method returns the value of its last expression;
returnis only needed to leave early. - Returning an array and assigning it to several names unpacks it:
low, high, mean = stats(...). - A block is code passed to a method in
{ }ordo ... end; the method runs it withyield. - Method names may end in
?(returns true/false, likeeven?) or!(changes the object or is the “dangerous” version, likesort!).