Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass on splat arguments in Ruby

Tags:

ruby

Given a class that has method which accepts a splat, for example a method you get from ActiveRecord::FinderMethods:

class Settle
  def self.find(*args)
  end
end

How should I call that method from another method, say another class, so that it has the exact same signature?

class Settler
  def self.find(*args)
    Settle.find(*args)
  end
end

Or

class Settler
  def self.find(*args)
    Settle.find(args)
  end
end

Or something else? Note that the exact same signature is the important part: Settler.find should work exactly similar to Settle.find.

I am not, however, interested in code that allows the Settler.find signature to magically update whenever Settle.find changes into something completely different, like e.g. .find(scope, *args). In that case, updating the version in Settler is no problem.

like image 655
berkes Avatar asked Sep 12 '25 08:09

berkes


1 Answers

It should be

Settle.find(*args)

This way, all the arguments passed into Settler.find, are passed also to Settle.find and stored in args array inside of it. So the args arrays inside of both methods hold the same value.

Passing arguments as 'splat' is quite simple - it's just passing an array as separate arguments. So if you have

ar = [arg1, arg2, arg3, argn]

calling

some_method(*ar)

is equivalent to

some_method(arg1, arg2, arg3, argn)
like image 173
Marek Lipka Avatar answered Sep 14 '25 21:09

Marek Lipka