jrichardlai
jrichardlai

Reputation: 3357

Is it possible to have a dynamic method call for default parameter values in Ruby?

I have a method which calls a method on an integer:

def print_time(time = 2.days.from_now)
  puts time
end

I tried in console it seems to work, but is this code safe? I mean by example:

Is the value (2.days.from_now) not evaluated only once when the method defined?

Thanks for helping me clarify! :)

Upvotes: 7

Views: 835

Answers (2)

steve
steve

Reputation: 3356

Well your question isn't particularly clear.

Are you worried about caching? Obviously something that is evaluated and then cached (ie, with action caching or page caching) will not be evaluated again until the cache has been cleared.

Or are you worried about the default argument value being cached when you define the method, and all subsequent calls might have the same value as a default? In this case, your console testing was valid and @Linux_iOS.rb.cpp.c.lisp.n (longest.name.evar) is correct -- Ruby does evaluate that expression each time.

Out of curiosity, what made you doubt your own testing in console?

Upvotes: 2

Linuxios
Linuxios

Reputation: 35803

Ruby evaluates the expression each time you call the method. So if you define it on Tuesday, and call it on Thursday, the result will be right.

Upvotes: 16

Related Questions