nanolab
nanolab

Reputation: 337

Count the identical string elements in Ruby array

I can't find a simple solution for this problem

For example we have an array:

["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]

I need to count the identical elements in this way:

[["a", 5], ["b", 2], ["c", 1], ["a", 3]]

Upvotes: 1

Views: 97

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

In Ruby 2.2 you could use Enumable#slice_when:

arr = ["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]

arr.slice_when { |e,f| e!=f }.map { |a| [a.first, a.size] }
  #=> [["a", 5], ["b", 2], ["c", 1], ["a", 3]]

Upvotes: 3

August
August

Reputation: 12568

Uses the chunk method to group identical elements, then uses map to convert [letter, array] pairs to [letter, count].

arr     = ["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]
counted = arr.chunk { |x| x }.map { |a, b| [a, b.count] } 
# => [["a", 5], ["b", 2], ["c", 1], ["a", 3]]

Upvotes: 4

Related Questions