inicio mail me! sindicaci;ón

Expressions as ruby default method arguments

When you use an expression as a ruby default argument like in

def delay(time=2.minutes.from_now)
  ... # stuff that needs to be done later
end

you might wonder, when exactly the expression gets evaluated, at parse time or at execution time. The difference, especially for time based expressions, can be huge!
Let’s find out:

puts 'A'
def delay(time=puts('B'))
end
puts 'C'
delay()

The output is

A
C
B

So it’s at execution time, which is much more useful anyway.

Schreibe einen Kommentar