Home > OS >  Ruby - Check the length of each words and group them
Ruby - Check the length of each words and group them

Time:07-08

I can't find the methods used to check the length of each word and group them per length.

arr = ["john","roger","matt","john", "james", "Jennifer"]

The method should return:

There are 3 names with 4 characters
There are 2 names with 5 characters
There is 1 names with 1 character

I tried this one and it's working

arr.group_by(&:length).transform_values(&:count)

Thank you

CodePudding user response:

this one will do

arr.map(&:size).tally

but you need Ruby versions >= 2.7

CodePudding user response:

each_with_object is your key.

arr = %w[john roger matt john james Jennifer]
res = 
  arr.each_with_object({}) do |name, obj|
    obj[name.length] ||= []
    obj[name.length].push(name)
  end
  •  Tags:  
  • ruby
  • Related