Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save priyankamk/965607ee3be4b44d3007ccced35e3ba0 to your computer and use it in GitHub Desktop.
Save priyankamk/965607ee3be4b44d3007ccced35e3ba0 to your computer and use it in GitHub Desktop.
How to compare two items(values) in an array - RUBY

Comparing two values in an array of numbers.

ar = [1,2,1,2,1,3,2]
ar.group_by{|x| x}.values.map {|x| x.size/2 }.reduce(&:+)
2

group_by

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

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.

Reduce

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:

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment