Reading — step 1 of 5
Learn
~1 min readMethods and Blocks
Methods are defined with def ... end. Parameter types aren't declared. The last evaluated expression is implicitly returned (no return needed).
def square(n)
n * n # last expression returned
end
puts square(5) # 25
Default values, splats, and keyword arguments make signatures very flexible:
def greet(name, greeting: "Hello", punct: "!")
"#{greeting}, #{name}#{punct}"
end
greet("Alice") # 'Hello, Alice!'
greet("Bob", greeting: "Hey") # 'Hey, Bob!'
def sum(*nums) # splat — variable args as array
nums.sum
end
sum(1, 2, 3) # 6
Method names ending in ? typically return a boolean. Ending in ! typically mutate the receiver or raise on failure.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…