How can I simplify or clean up this anagram method?

前端 未结 2 1586
清歌不尽
清歌不尽 2021-01-07 14:48

I have a method here that takes an array of strings and groups the ones that are anagrams of each other together, with each group forming a sub-array of the main anagr

2条回答
  •  一生所求
    2021-01-07 15:23

    I modified sawa's answer slightly in order to ignore case and make sure there's no duplicate values:

    test_words.group_by{|w| w.downcase.each_char.sort}.values.each{|v| v.uniq!}
    

    I realize this will still give duplicates in the output if the words have characters with different cases, but that's fine for my purposes. Now I'm all sorted, thanks!

提交回复
热议问题