Feature #8827

A method that flips the receiver and the first argument

Added by Tsuyoshi Sawada about 2 years ago. Updated about 2 years ago.



If it often happens that we need to pass to a method an argument that is the result of a long chain of operations:





I believe one basic tenet of Ruby is to encourage method chaining, but that practice is discouraged in the examples above. It would be convenient if there is a method (let us call this Object#flip) that flips the receiver and the first argument and sends the method so that the examples above can be written as follows:

some_chain_of_operations_that_ends_up_with_an_array.flip(Hash, :[])

some_chain_of_operations_that_ends_up_with_a_string.flip(File, :read)

some_chain_of_operations_that_ends_up_with_an_object.flip(YAML, :dump)


The implementation in Ruby may be as follows:

class Object
  def flip receiver, method, *rest, &pr
    receiver.send(method, self, *rest, &pr)

It would be good if we can have that as a built-in Ruby method.



#1 Updated by Nobuyoshi Nakada about 2 years ago

You can write as:

some_chain_of_operations_that_ends_up_with_an_array.tap {|ary| Hash[ary]}
some_chain_of_operations_that_ends_up_with_a_string.tap {|path| File.read(path)}
some_chain_of_operations_that_ends_up_with_an_object.tap {|obj| YAML.dump(obj)}

#2 Updated by Tsuyoshi Sawada about 2 years ago

nobu, I think you mean tap{|ary| break ...}, etc. That does not look concise enough for me. It might look like a small difference, but it makes huge difference when you are in the middle of a chain. It saves you from thinking extra things.

#3 Updated by Charlie Somerville about 2 years ago




#4 Updated by Tsuyoshi Sawada about 2 years ago

charliesome, that has the same problem as nobu's. It does not return the final result. It gives back the receiver.

#5 Updated by Alexey Muranov about 2 years ago

I think this request is mostly a duplicate of #6721.

Also available in: Atom PDF