RbRuby

Ruby: Functions – code examples

Contents

Method with Keyword Argument

Functions#def#method#keyword argumentCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
def begruesse(name, gruss: "Hello")
  "#{gruss}, #{name}!"
end

puts begruesse("Ada")
puts begruesse("Linus", gruss: "Hi")

Functions are called methods in Ruby (def). The last expression is the return value, gruss: is an optional keyword argument with a default value.

Your Own Method with a Block (yield)

Functions#block#yield#timing
Use case: Encapsulate recurring framing logic, e.g. timing, logging or cleanup.
def messen(name)
  start = Time.now
  ergebnis = yield
  dauer = ((Time.now - start) * 1000).round(1)
  puts "#{name}: #{dauer} ms"
  ergebnis
end

summe = messen("Sum") { (1..1_000_000).map { |x| x * x }.sum }
puts summe

yield executes the passed block; the return value of the block becomes the result of yield. This is how you build your own each- and File.open-style methods.

Lambda, Proc and &:symbol

Functions#lambda#proc#symbol to_proc#closure
Use case: Store and pass on behavior, e.g. filters, discount rules or callbacks.
rabatt = ->(preis, prozent) { (preis * (100 - prozent) / 100.0).round(2) }
puts rabatt.call(80, 25)
puts rabatt.(200, 10)

verdoppeln = proc { |x| x * 2 }
puts [1, 2, 3].map(&verdoppeln).inspect
puts %w[ruby php].map(&:capitalize).inspect

Lambdas are strict about the number of arguments, Procs are generous. & turns a Proc or symbol into a block; &:capitalize calls the method on each element.