A method that applies itself to a process

I want to have a method defined in Object that takes a block and applies the receiver to the block. The implementation will look like this:

 class Object def apply ≺ pr.call(self) end end 2.apply{|x| x * 3} # => 6 

Is there a standard way to do this or a well-known library that has a method with similar usage? If so, I did not want to reinvent the wheel.

It very often happens to me that I have a method that accepts an optional block, and when there is no block, I want to return some return_value calculated in the method, but when there is a block, I want to return the return value return_value applied to the block. So far I have bundles of strings like:

 def method ..., &pr ... pr ? pr.call(return_value) : return_value end 

but I want to write consistently

 def method ..., &pr ... pr ? return_value.apply(&pr) : return_value end 

or even better, with a slightly modified definition of apply ,

 def method ..., &pr ... return_value.apply(&pr) end 
0
source share
3 answers

I think Object.tap is what you are looking for:

 "Abc".tap do |str| puts str end 
+3
source

It is not identical to def apply; yield self; end def apply; yield self; end def apply; yield self; end ? - steenslag

@steenslag Yes. It. I want to have this effect with self as a receiver. - sawa

Is that what you mean?

 2.instance_eval { * 3 } # => 6 

Unfortunately this does not work. instance_eval just runs the code as if the receiver was self . Operators do not assume self as a receiver, so you really need to write this:

 2.instance_eval { self * 3 } # => 6 

However, as a proof of concept, this is possible:

 Numeric.send(:define_method, :plus) { |x| self + x } 2.instance_eval { plus 3 } # => 5 
+1
source

(Aftwer reading OP edit) AFAIK canonical way to write this:

 def purpose(*args) #no &bl or &pr res = 42 #huge calculation return res unless block_given? yield res end p purpose(1,2) purpose{|n| puts "from the block: #{n}"} 
0
source

Source: https://habr.com/ru/post/927515/


All Articles