Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • I run my server with cache caching enabled
  • I call the method which prints 2 days later
  • 1 hour later the value printed will be really 1 hour + 2 days later?

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

Thanks for helping me clarify! :)

like image 254
jrichardlai Avatar asked Apr 02 '12 19:04

jrichardlai


2 Answers

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.

like image 75
Linuxios Avatar answered Oct 07 '22 14:10

Linuxios


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?

like image 27
steve Avatar answered Oct 07 '22 13:10

steve