1

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]]
1
  • That is not a valid Ruby code. Commented Jan 11, 2015 at 21:18

2 Answers 2

4

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it fixed a similar problem I have, which I need sort it first. counted = arr.sort.chunk { |x| x }.map { |a, b| [a, b.count] }
3

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]]

2 Comments

oh,2.2 version have a new method #slice_when.
@user3673267, also Enumerable#slice_after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.