ar = [1,2,1,2,1,3,2]
ar.group_by{|x| x}.values.map {|x| x.size/2 }.reduce(&:+)
2
group_by() public
Returns a hash, which keys are evaluated result from the block, and values are arrays of elements in enum corresponding to the key.
If no block is given, an enumerator is returned instead. result
(1..6).group_by {|i| i%3} #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
Map enumerates through the array of elements and transform the given values and returns as array. The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!)
Array and Range are enumerable types. map with a block returns an Array. map! mutates the original array.
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
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 uses the first element of collection is used as the initial value of memo.
Examples:
(5..10).reduce(:+) #=> 45
(5..10).inject {|sum, n| sum + n } #=> 45
(5..10).reduce(1, :*) #=> 151200
(5..10).inject(1) {|product, n| product * n } #=> 151200
longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=> "sheep"