ruby get the number of same element in array
# Sample array
array = [1, 2, 3, 2, 1, 2, 4]
# Count occurrences of each element
element_count = array.each_with_object(Hash.new(0)) { |element, count| count[element] += 1 }
# Display the count of each element
element_count.each { |element, count| puts "#{element} appears #{count} times" }
Explanation of each step:
array = [1, 2, 3, 2, 1, 2, 4]
: This line initializes an array namedarray
with multiple elements.element_count = array.each_with_object(Hash.new(0)) { |element, count| count[element] += 1 }
: This line uses theeach_with_object
method to iterate through thearray
elements. It initializes an empty hash with a default value of 0 (Hash.new(0)
) and counts occurrences of each element by incrementing the count for that element in the hash.element_count.each { |element, count| puts "#{element} appears #{count} times" }
: This line iterates through theelement_count
hash and prints the count of each element in the format:"element appears count times"
using string interpolation. It displays the count of each unique element in the array.