RubyA trick with the Ruby documentation

Fran C.

Fran C.

2 minutes read

I've never been able to remember the arguments for Array#reduce. Every time I think I've managed to do it I just get it wrong.

Luckily for me, Ruby has very good documentation on its standard library and, what's even better, it ships with a CLI to explore it so I don't even need to Google it 😬

1 ri "Array#reduce"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 = Array#reduce (from ruby core) === Implementation from Enumerable ------------------------------------------------------------------------ enum.reduce(initial, sym) -> obj enum.reduce(sym) -> obj enum.reduce(initial) { |memo, obj| block } -> obj enum.reduce { |memo, obj| block } -> obj ------------------------------------------------------------------------ Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. The inject and reduce methods are aliases. There is no performance benefit to either. If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method. If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo. # Sum some numbers (5..10).reduce(:+) #=> 45 # Same using a block and inject (5..10).inject { |sum, n| sum + n } #=> 45 # Multiply some numbers (5..10).reduce(1, :*) #=> 151200 # Same using a block (5..10).inject(1) { |product, n| product * n } #=> 151200 # find the longest word longest = %w{ cat sheep bear }.inject do |memo, word| memo.length > word.length ? memo : word end longest #=> "sheep"

It has a very good interactive mode as well (ri -i) In which you can search whatever you want :)

Oh, and if you use Vim you can access it by using K over any word. Check this out:

Fran C.
Staff Software Engineer

I break code for a living... wait no, I fix it, most of the time. Well, sometimes. Yeah, I break code for a living.

Liked this read?Join our team of lovely humans

We're looking for outstanding people like you to become part of our team. Do you like shipping code that adds value on a daily basis while working closely with an amazing bunch of people?

Made with ❤️ by Factorial's Team