Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby排序和消除重复_Ruby_Arrays_List_Sorting_Methods - Fatal编程技术网

Ruby排序和消除重复

Ruby排序和消除重复,ruby,arrays,list,sorting,methods,Ruby,Arrays,List,Sorting,Methods,我有一个列表,我需要按最流行的元素进行排序。有没有办法做到这一点 在我重新排序之后,我还需要去掉重复的。我想到了一个函数,但它似乎效率很低,那么有没有内置的方法来帮助实现这一点?迭代列表以构建一个映射项->次数的散列,只需访问列表中的所有元素一次,那么散列的操作将是常数时间,依此类推,这似乎没有那么昂贵。通过遍历列表来构建一个映射项->次数的哈希,只需访问列表中的所有元素,那么哈希的操作将是常量时间,依此类推,这似乎没有那么昂贵。该方法使用可选谓词来比较两个元素,因此 list.sort { |

我有一个列表,我需要按最流行的元素进行排序。有没有办法做到这一点


在我重新排序之后,我还需要去掉重复的。我想到了一个函数,但它似乎效率很低,那么有没有内置的方法来帮助实现这一点?

迭代列表以构建一个映射项->次数的散列,只需访问列表中的所有元素一次,那么散列的操作将是常数时间,依此类推,这似乎没有那么昂贵。

通过遍历列表来构建一个映射项->次数的哈希,只需访问列表中的所有元素,那么哈希的操作将是常量时间,依此类推,这似乎没有那么昂贵。

该方法使用可选谓词来比较两个元素,因此

list.sort { |a, b| a.popularity <=> b.popularity }
把它们粘在一起

list = list.sort { |a, b| a.popularity <=> b.popularity }.unique
或者干脆

list.sort! { |a, b| a.popularity <=> b.popularity }.uniq!
该方法使用可选谓词来比较两个元素,因此

list.sort { |a, b| a.popularity <=> b.popularity }
把它们粘在一起

list = list.sort { |a, b| a.popularity <=> b.popularity }.unique
或者干脆

list.sort! { |a, b| a.popularity <=> b.popularity }.uniq!
像那样


像这样?

uniq方法需要一个块,因此您可以指定对象的哪个“属性”必须是uniq

new_list = list.sort_by{|el| el.popularity}.uniq{|el| el.popularity}

uniq方法接受一个块,因此您可以指定对象的哪个“属性”必须是uniq

new_list = list.sort_by{|el| el.popularity}.uniq{|el| el.popularity}

大多数答案对我都不起作用,除了格伦麦当劳,直到我发布了这个答案 我在别的地方找到了我自己问题的答案

list = [2,1,4,4,4,1] #for example
count = Hash.new(0)
list.each {|element| count[element] += 1} #or some other parameter than element
list = list.uniq.sort {|x,y| count[y] <=> count[x]}

大多数答案对我都不起作用,除了格伦麦当劳,直到我发布了这个答案 我在别的地方找到了我自己问题的答案

list = [2,1,4,4,4,1] #for example
count = Hash.new(0)
list.each {|element| count[element] += 1} #or some other parameter than element
list = list.uniq.sort {|x,y| count[y] <=> count[x]}