There has to be a built in way of doing this, right?
class Object def send_chain(arr) o=self arr.each{|a| o=o.send(a) } return o end end
Method chaining is a convenient way to build up complex queries, which are then lazily executed when needed. Within the chain, a single object is updated and passed from one method to the next, until it's finally transformed into its output value.
Send method basics Typically dot notation is used to a call method on an object. In the code snippet just below, on line 2 the + method is called on the integer object. The send method works similarly to dot notation. The send method invokes the method identified by symbol, passing it any arguments specified.
Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name.
We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.
I just ran across this and it really begs for inject:
def send_chain(arr) arr.inject(self) {|o, a| o.send(a) } end
Building upon previous answers, in case you need to pass arguments to each method, you can use this:
def send_chain(arr) Array(arr).inject(self) { |o, a| o.send(*a) } end
You can then use the method like this:
arr = [:to_i, [:+, 4], :to_s, [:*, 3]] '1'.send_chain(arr) # => "555"
This method accepts single arguments as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With