How can I simplify or clean up this anagram method?

前端 未结 2 1587
清歌不尽
清歌不尽 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:10
    test_words.group_by{|w| w.each_char.sort}.values
    

    would give

    [
      ["cars", "racs", "scar"],
      ["for"],
      ["potatoes"],
      ["four"],
      ["creams", "scream"]
    ]
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题