check same number in array ruby code example
Example 1: ruby get the number of same element in array
names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
counts = Hash.new(0)
names.each { |name| counts[name] += 1 }
# => {"Jason" => 2, "Teresa" => 1, ....
Example 2: ruby get the number of same element in array
names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
counts = names.each_with_object(Hash.new(0)){ |string, hash| hash[string] += 1 }
puts counts # => { Jason: 2, Teresa: 1, Judah: 3, ... }