Array.sort!{| element | Array.count(element)}有什么作用?

时间:2017-11-07 07:02:37

标签: arrays ruby sorting

我想按照它们出现在数组中的频率对数组中的一些字符串进行排序。我知道我可以使用sort_by来实现这一点,但我偶然使用了这段代码 items.sort!{| x | items.count(x)} 并想知道列表发生了什么。< / p>

items = ["apple", "pineapple", "apple", "apple", "orange", "orange", "grape"]
items.sort!{|x|items.count(x)}
items = ["grape", "apple", "apple", "orange", "apple", "orange", "pineapple"]

items = ["apple", "pineapple", "apple", "apple", "orange", "orange", "grape", "pineapple", "apple", "orange"]
items.sort!{|x|items.count(x)}
items = ["orange", "orange", "apple", "grape", "apple", "pineapple", "orange", "apple", "apple", "pineapple"]

0 个答案:

没有答案