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:

  1. array = [1, 2, 3, 2, 1, 2, 4]: This line initializes an array named array with multiple elements.

  2. element_count = array.each_with_object(Hash.new(0)) { |element, count| count[element] += 1 }: This line uses the each_with_object method to iterate through the array 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.

  3. element_count.each { |element, count| puts "#{element} appears #{count} times" }: This line iterates through the element_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.