BeginnerLesson 5 of 16
Defining Methods – Ruby
def, default values, keyword arguments, splat and the implicit return value.
You define a method with def. The value of the last expression is returned automatically – you only need return for leaving early. Besides normal parameters there are keyword arguments (gruss:), which make calls readable.
def begruesse(name, gruss: "Hello")
"#{gruss}, #{name}!" # last expression = return value
end
puts begruesse("Ada")
puts begruesse("Linus", gruss: "Hi")With *args you collect any number of positional arguments in an array, with opts any keyword arguments in a hash. Since Ruby 3.0 there is also the endless method** for one-liners.
def summe(*zahlen) = zahlen.sum # since Ruby 3.0
puts summe(1, 2, 3, 4) # 10
def profil(name, alter = nil, *hobbys, stadt:, **extra)
puts "#{name}, #{alter.inspect}, #{stadt}"
puts "Hobbies: #{hobbys.inspect}, Extra: #{extra.keys.inspect}"
end
profil("Ada", 36, "Reading", "Math", stadt: "London", beruf: "Author")Conventions: methods ending in ? return a boolean (empty?, even?), methods ending in ! are the "more dangerous" variant (usually: modifies the object itself).
def gerade?(n) = n.even?
puts gerade?(4) # true
liste = [3, 1, 2]
puts liste.sort.inspect # [1, 2, 3] – new list, liste stays unchanged
puts liste.inspect # [3, 1, 2]
liste.sort! # modifies liste itself
puts liste.inspect # [1, 2, 3]Warning
? and ! at the end of a method name are only a convention, not a language feature – stick to it for your own methods. And with nested calls without parentheses (puts foo bar) things quickly become ambiguous: use parentheses then.TipWith
method(:name) you get a method object that you can pass like a block: [1, 2].each(&method(:puts)).