gpt4 book ai didi

ruby - 有人可以解释为什么这个用于查找字谜的 ruby 代码有效吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:20:29 24 4
gpt4 key购买 nike

这是一行:

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

words 是一个单词数组,如果它们与原始数组中的另一个单词共享相同的字母,则这些单词将被分组。有人可以深入了解一下这是如何工作的吗?

最佳答案

好吧,让我们一一过一遍这些方法:

group_by:是一种采用Enumerable(在本例中为数组)和 block 的方法。它将数组中的每个值传递给 block ,然后查看 block 的结果。然后它返回一个哈希,其中键是 block 的结果,值是具有相同结果的原始输入的数组。

downcase:获取一个字符串并将其全部小写

chars:将字符串转换为字符数组

sort:对集合进行排序

values:仅返回 Hash 的值。

有了这些定义,让我们回到您的代码:

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

"Take each word in the array of words, make it lowercase, then sort its letters into alphabetical order. The words that contain exactly the same letters will have the same sorted result, so we can group them into a Hash of Arrays, with the sorted letters as the key and the Array of matching words as the value. We don't actually care what the actual letters are, just the words that share them, so we take only the Arrays (the values)."

举个例子:

words = %w[throw worth threw Live evil]
# => [ 'throw', 'worth', 'threw', 'Live', 'evil' ]
words_hash = words.group_by {|word| word.downcase.chars.sort}
# => {
# 'eilv' => [ 'evil', 'Live' ],
# 'ehrtw' => [ 'threw'],
# 'hortw' => [ 'throw', 'worth']
# }

words_hash.values
# => [['evil', 'Live'], ['threw'], ['throw', 'worth']]

关于ruby - 有人可以解释为什么这个用于查找字谜的 ruby 代码有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com