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