使用 Split 和 Join 的 Ruby Key

标签 ruby

我这里有笔试,这是说明。

Write a program that prints out groups of words that are anagrams. Anagrams are words that have the same exact letters in them but in a different order. Your output should look something like this:

["demo", "dome", "mode"]
["neon", "none"]

(等)

解决方法如下:

words =  ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
          'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
          'flow', 'neon']


result = {}

words.each do |word|
  key = word.split('').sort.join
  if result.has_key?(key)
    result[key].push(word)
  else
    result[key] = [word]
  end
end

result.each do |k, v|
  puts "------"
  p v
end

我一直试图理解 ruby​​ 代码解决方案,但不能轻易掌握它。我的问题之一是,如果 result 哈希没有键或其中包含任何元素,您如何测试它。 .join 和 .sort 如何处理此代码。

我真的很困惑这一切是如何通过答案的。有哪位大牛能把这段代码逐行解释清楚,通俗易懂,像我这样的初学者都能看懂吗?

最佳答案

我会这样做:

words =  ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
      'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
      'flow', 'neon']

words.group_by { |word| word.chars.sort }.values

#=> [["demo","dome","mode"],["none","neon"],["tied","diet","edit","tide"],["evil","live","veil","vile"],["fowl","wolf","flow"]]

关于使用 Split 和 Join 的 Ruby Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39200885/

相关文章:

ruby - 如何使用 Ruby 在 Selenium WebDriver Remote 上设置 firefox 配置文件

ruby-on-rails - 我如何用 Rails 交换这个链接?

ruby-on-rails - 将参数传递给局部 View - Rails 4/postgresql/json

Ruby命令行脚本不连续执行代码

ruby-on-rails - Rails 地理编码模型中的两种方式

ruby - #<Bundler::Dsl:0x007fc17c3fc6c8> (NoMethodError) 的未定义方法 `ruby'

ruby - 从数组中删除空格、制表符和新行

javascript - Ruby on Rails,ajax 分页错误,在更改站点之前有效

ruby-on-rails - Rails 模型变量意外更改

ruby - 正则表达式,如何在 ruby​​ 中查找文件?