artis3n
artis3n

Reputation: 840

Ruby - Passing functions as arguments

I want to pass two functions as methods like so:

def add_user_review(user_id, movie_id, set=:training)
  check_set set, @training_data.add_user_review(user_id, movie_id), @test_data.add_user_review(user_id, movie_id)
end

where the check_set method looks like:

# If set is training set, initiate training set function. else, initiate test set function
def check_set(set, training_method, test_method)
  set == :training ? training_method : test_method
end

I have methods that behave one of two ways depending on set (either :training or :test). Both @training_data and @test_data are objects from another class, and training_method will always be called on @training_data, likewise for test_method and @test_data. Each method accepts different parameters (i.e. not all are passing user_id and movie_id).

I need to refactor my code to incorporate a Proc or something. What should I do?

Upvotes: 0

Views: 420

Answers (1)

Ismael
Ismael

Reputation: 16710

Here is a simple implementation with procs. The proc only gets executed when you do call on it.

 def add_user_review(user_id, movie_id, set=:training)
    check_set set, proc { @training_data.add_user_review(user_id, movie_id) }, proc { @test_data.add_user_review(user_id, movie_id) }
  end

 def check_set(set, training_method, test_method)
   set == :training ? training_method.call() : test_method.call()
 end

Upvotes: 2

Related Questions