pandaman pandaman - 6 months ago 7
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 = Time.now

function(input)

end = Time.now
end - beg
end


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

def double(value)
value + value
end

p track_time(double, 5)


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

Answer

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 = Time.now
  send method, value
  end_time = Time.now
  end_time - begin_time
end

def double(value)
    value + value
end

p trcak_time(:double, 5)