数组的ruby排序数组

时间:2022-05-11 16:00:14

I'm having a problem figuring out how I can sort an array of an array. Both arrays are straight forward and I'm sure it's quite simple, but I can't seem to figure it out.

我有个问题要解决如何对数组排序。这两个数组都是直接的,我确定这很简单,但我似乎无法理解。

Here's the array:

数组:

[["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]

I want to sort it by the integer value of the inner array which is a value of how many times the word has occurred, biggest number first.

我想通过内部数组的整数值对它进行排序它是单词出现的次数的值,首先是最大的数字。

4 个解决方案

#1


30  

Try either:

试一试:

array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| a[1] <=> b[1]}

Or:

或者:

array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| b[1] <=> a[1]}

Depending if you want ascending or descending.

这取决于你想要提升还是下降。

#2


2  

sort can be used with a block.

排序可以与块一起使用。

a = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
a.sort { |o1, o2| o1[1] <=> o2[1] }
#=> [["happy", 1], ["mad", 1], ["sad", 2], ["bad", 3], ["glad", 12]] 

#3


1  

Using the Array#sort method:

使用数组排序方法:

ary = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
ary.sort { |a, b| b[1] <=> a[1] }

#4


1  

This should do what you want.

这应该是你想要的。

a = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
a.sort {|x,y| y[1] <=> x[1]}

#1


30  

Try either:

试一试:

array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| a[1] <=> b[1]}

Or:

或者:

array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| b[1] <=> a[1]}

Depending if you want ascending or descending.

这取决于你想要提升还是下降。

#2


2  

sort can be used with a block.

排序可以与块一起使用。

a = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
a.sort { |o1, o2| o1[1] <=> o2[1] }
#=> [["happy", 1], ["mad", 1], ["sad", 2], ["bad", 3], ["glad", 12]] 

#3


1  

Using the Array#sort method:

使用数组排序方法:

ary = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
ary.sort { |a, b| b[1] <=> a[1] }

#4


1  

This should do what you want.

这应该是你想要的。

a = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
a.sort {|x,y| y[1] <=> x[1]}