Ruby-将数组分为子类别
假设我有一个单词数组,比如:Ruby-将数组分为子类别,ruby,Ruby,假设我有一个单词数组,比如: words = ["apple", "zebra", "boat", "dog", "ape", "bingo"] 我想按字母顺序对它们进行排序,但将它们按如下方式分组: sorted = [["ape", "apple"], ["bingo", "boat"], ["dog"], ["zebra"]] 我怎样才能在Ruby中做到这一点?感谢您的帮助。像这样的事情应该可以奏效 words = ["apple", "zebra", "boat", "dog", "
words = ["apple", "zebra", "boat", "dog", "ape", "bingo"]
我想按字母顺序对它们进行排序,但将它们按如下方式分组:
sorted = [["ape", "apple"], ["bingo", "boat"], ["dog"], ["zebra"]]
我怎样才能在Ruby中做到这一点?感谢您的帮助。像这样的事情应该可以奏效
words = ["apple", "zebra", "boat", "dog", "ape", "bingo"]
sorted = words.sort.group_by { |s| s[0] }.map { |k,v| v }
我假设你正试图按照每个单词的第一个字母来分组。在这种情况下,可以使用对数组进行排序,并根据每个单词的第一个字符进行分组(由返回)
你可以这样做:
words.sort.chunk { |s| s[0] }.map(&:last)
首先按字母顺序对数组进行排序(
.sort
),然后将具有相同第一个字符的元素(“chunk”{code>.chunk{s | s[0]}),然后从每个子数组中获取最后一个元素。在本例中,字母表中的字母。下面是使用嵌套循环查找的内容
words = ["apple", "zebra", "boat", "dog", "ape", "bingo"]
results = []
('a'..'z').to_a.each_with_index do |letter, index|
letter_result = []
words.each do |word|
if(word[0]==letter)
letter_result.push(word)
end
end
unless letter_result.empty?
results.push(letter_result)
end
end
“斯特凡,我想<代码> GROPYBY(&:CHR)使代码比<代码> GROPY更可读,{{s s [0 ] }(避免中间行中的块)。我已经编辑了我的答案。谢谢。分组的条件是什么?
words = ["apple", "zebra", "boat", "dog", "ape", "bingo"]
results = []
('a'..'z').to_a.each_with_index do |letter, index|
letter_result = []
words.each do |word|
if(word[0]==letter)
letter_result.push(word)
end
end
unless letter_result.empty?
results.push(letter_result)
end
end