Method returning object revenue in Ruby

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

For example, what if I have an object that I want to put into an array?

In an ideal world, we will do (what I am looking for):

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

which will return an array with my object, as the equivalent:

 send("string".reverse.upcase) 

which is not chain related if I have my object to start with it and can get confused in more complex scenarios.

Thus, the something method returns a block estimate, for example Array#map , but for only one element.

+4
source share
4 answers

I do not know such an embedded device, but you can easily do it yourself:

 class Object def something(&block) block.call(self) end end p "foo".something { | o | [o] } p 23.something { | x | px; 42 } 

gives

 ["foo"] # object "foo" put into an array 23 # object handed to block 42 # something return block result 
+4
source

Are you looking for Object.tap ?

+1
source

Sometimes I need a similar function in the standard library. This name can be, for example, with or with_it

(Repeating the previous code with a new name)

 class Object def with_it(&block) block.call(self) end end 

Usage example:

 x = [1, 2, 3, 4, 5].map {|x| x * x }.with_it do |list| head = list.unshift list << head * 10 list.join " / " end 

Unlike:

 list = [1, 2, 3, 4, 5].map {|x| x * x } head = list.unshift list << head * 10 x = list.join " / " 

While the latter is easier to understand, the former has the advantage of keeping the list and head variables in scope and the x assignment is clearer in my opinion (the assignment x should be inserted in the last line of code). Priority would be useful if the code was part of a larger method.

Another use with_it would therefore be to put the code in a separate method. For instance:

 def mult_head_and_join(list) head = list.unshift list << head * 10 list.join " / " end x = mult_head_and_join [1, 2, 3, 4, 5].map {|x| x * x } 

Not sure what to conclude here, but I think I would vote for with_it to be included in the standard library

+1
source

Six years after the initial question, Ruby 2.5.0 introduces Object#yield_self :

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

[...]

It executes a block and returns its output. For instance:

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

( Ruby Feature # 6721 )

Rubies are happy!

+1
source

All Articles