tim_xyz
tim_xyz

Reputation: 13561

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.

Upvotes: 1

Views: 71

Answers (3)

Mladen Jablanović
Mladen Jablanović

Reputation: 44100

Unfortunately, methods in Ruby are not first-class objects, so they can't be directly passed as arguments. You can pass a name of the method (usually passed as symbol) instead, as other answers suggest.

But the idiomatic way to achieve what you are aiming for are blocks:

def track_time
  start = Time.now

  yield

  finish = Time.now
  finish - start
end

track_time do
  double(5)
end
#=> 6.127e-06

Upvotes: 3

kirlev
kirlev

Reputation: 700

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)

Upvotes: 3

Nabeel
Nabeel

Reputation: 2302

Remember that end is a reserved word in Ruby (I suspect it was for illustration purposes anyhow).

You could pass in the string/symbol of the function name instead.

def track_time(function, input)
  start = Time.now

  method(function).call(input)

  finish = Time.now
  finish - start
end

def double(value)
  value + value
end

track_time('double', 5)
=> 6.127e-06

Upvotes: 2

Related Questions