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

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

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

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

  • I start my server with cache caching.
  • I call a method that prints in 2 days
  • After 1 hour, will the printed value be valid 1 hour + 2 days later?

Is the value (2.days.from_now) specified only once when defining a method?

Thank you for helping me clarify! :)

+7
source share
2 answers

Well, your question is not particularly clear.

Are you worried about caching? Obviously, what is evaluated and then cached (i.e., with action caching or page caching) will not be evaluated again until the cache is cleared.

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

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

+2
source

Ruby evaluates an expression every time you call a method. Therefore, if you determine it on Tuesday and call on Thursday, the result will be correct.

+14
source

All Articles