http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf如何將單詞數組排序爲Ruby中的字符串數組?
試圖參與本作業的第3部分。下面的代碼似乎沒有工作,即對參數['HeLLo', 'hello']
,返回[["hello"], ["HeLLo"]]
代替[["HeLLo", "hello"]]
def combine_anagrams(words)
#iterate through words, make hashmap with the sorted version
hash = {}
words.each do |x|
hash[x.chars.sort.join.downcase.gsub /\W/, ""] = []
end
#iterate through words, access hashmap and append curr to array
words.each do |x|
hash[x.chars.sort.join.downcase.gsub /\W/, ""] << x
end
hash.values #return array of values
end
任何幫助,將不勝感激。 (我是新來的Ruby)
給我們輸入的字符串,並預期輸出。 – 2013-04-06 20:18:03
這個問題就在前些日子,搜索了一下。另外,如果你想分組,也許'group_by'方法是你應該看的。 – tokland 2013-04-06 20:18:28
試試這個'hash.values.flatten(1).reverse.each_cons(2){| x | p [x]} – 2013-04-06 20:25:00