Search code examples
rubyobjectblockyieldchainability

Method that returns the yield for an object in Ruby


Is there a method in Ruby that returns the content of the block passed on to an object?

For example, what if I have an object which I want to put in an array?

In an ideal world, we would do (what I'm looking for):

"string".reverse.upcase.something{ |s| send(s) }

which would return an array with my object, as equivalent to:

send("string".reverse.upcase)

which isn't chainable if I have my object to start with and can get messy in more complex scenarios.

So the something method would return the evaluation of the block, like Array#map, but for one element only.


Solution

  • Six years after the original question, Ruby 2.5.0 introduced Object#yield_self, then shortened in Ruby 2.6 as #then:

     class Object
       def yield_self(*args)
         yield(self, *args)
       end
     end
    

    [...]

    It executes the block and returns its output.

    (Ruby Feature #6721)

    For example:

    2.then{ |x| x*x }  # => 4