pandaman pandaman - 1 year ago 60
Ruby Question

How to pass a parameter to a method that is also a parameter itself in Ruby?

*Apologies if the question's wording is confusing. I didn't know exactly how to ask it.

How can I do something like this?

def track_time(function, input)
beg =


end =
end - beg

And then pass it a function and a value for that function to use.

def double(value)
value + value

p track_time(double, 5)

The goal is to create something repeatable so I can track how long different functions take to complete.

Answer Source

First you can not use 'end' as a variable name.

As for your question, I agree with Mladen Jablanovićyou that for this use case a block is better, but since you specifically asked about passing a method as a parameter to another method, you can use the 'send' method:

def track_time method, value
  begin_time =
  send method, value
  end_time =
  end_time - begin_time

def double(value)
    value + value

p trcak_time(:double, 5)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download