Any standard method similar to tap but returning the result of a block instead of self?

Let's say I have an array of time durations expressed in minutes:

minutes = [20, 30, 80] 

I would like to summarize the contents of the array and output the result in the format <hours>:<minutes> . In the above example, I expect the result to be 02:10 .

Is there any standard Ruby method (i.e. included in core or std-lib) that allows you to do this in a single-line method chain? (that is, without using a variable to store the intermediate result). I mean something like:

 puts minutes.reduce(:+).foomethod { |e| sprintf('%02d:%02d', e / 60, e % 60) } 

What should be foomethod ? Object.tap is pretty close to what I need, but unfortunately it returns self, not the result of the block.

+5
source share
2 answers

Try this one

 puts sprintf('%02d:%02d', *minutes.reduce(:+).divmod(60)) 
+3
source
 proc { |e| sprintf('%02d:%02d', e / 60, e % 60) }.call(minutes.reduce(:+)) #=>"01:00" 

or if you prefer lambdas

 ->(e) { sprintf('%02d:%02d', e / 60, e % 60) }.call(minutes.reduce(:+)) #=>"01:00" 

PS: If you want to make it even shorter, you can also use [] and .() To call lambda, i.e.

 ->(e) { sprintf('%02d:%02d', e / 60, e % 60) }.(minutes.reduce(:+)) #=>"01:00" ->(e) { sprintf('%02d:%02d', e / 60, e % 60) }[minutes.reduce(:+)] #=>"01:00" 
+3
source

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


All Articles