Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to chain multiple method calls together with "send"

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 
like image 955
Zando Avatar asked Nov 04 '10 17:11

Zando


People also ask

Can you chain methods in Ruby?

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.

How do you use the send method in Ruby?

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.

How to define methods in Ruby?

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.

What is method call in Ruby?

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.


2 Answers

I just ran across this and it really begs for inject:

def send_chain(arr)   arr.inject(self) {|o, a| o.send(a) } end 
like image 51
Joe Avatar answered Sep 28 '22 05:09

Joe


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.

like image 26
dgilperez Avatar answered Sep 28 '22 05:09

dgilperez