I have an array named @level1
which has a value like this:
我有一个名为@level1的数组,它的值如下:
[
[3.1, 4],
[3.0, 7],
[2.1, 5],
[2.0, 6],
[1.9, 3]
]
I want to split this into two arrays such that the first array (@arr1
) contains the values till 2.1
and the second array (@arr2
) contains values after it.
我想把它分成两个数组,以便第一个数组(@arr1)包含直到2.1的值,第二个数组(@arr2)包含其后的值。
After doing that, I would reverse-sort my second array by doing something like this:
在此之后,我将对第二个数组进行反向排序,方法如下:
@arr2 = @arr2.sort_by { |x, _| x }.reverse
I would then like to merge this array to @arr1
. Can someone help me how to split the array and then merge them together?
然后我想将这个数组合并到@arr1。有人能帮我拆分数组然后合并它们吗?
2 个解决方案
#1
54
Try the partition method
试的分区方法
@arr1, @arr2 = @level1.partition { |x| x[0] > 2.1 }
The condition there may need to be adjusted, since that wasn't very well specified in the question, but that should provide a good starting point.
可能需要调整的条件,因为在问题中没有很好地说明,但是这应该提供一个好的起点。
#2
1
something like this?
是这样的吗?
arr = [
["3.1", 4],
["3.0", 7],
["2.1", 5],
["2.0", 6],
["1.9", 3]
]
arr1, arr2 = arr.inject([[], []]) do |f,a|
a.first.to_f <= 2.1 ? f.last << a : f.first << a; f
end
arr = arr1 + arr2.reverse
=> [["3.1", 4], ["3.0", 7], ["1.9", 3], ["2.0", 6], ["2.1", 5]]
See it running here
#1
54
Try the partition method
试的分区方法
@arr1, @arr2 = @level1.partition { |x| x[0] > 2.1 }
The condition there may need to be adjusted, since that wasn't very well specified in the question, but that should provide a good starting point.
可能需要调整的条件,因为在问题中没有很好地说明,但是这应该提供一个好的起点。
#2
1
something like this?
是这样的吗?
arr = [
["3.1", 4],
["3.0", 7],
["2.1", 5],
["2.0", 6],
["1.9", 3]
]
arr1, arr2 = arr.inject([[], []]) do |f,a|
a.first.to_f <= 2.1 ? f.last << a : f.first << a; f
end
arr = arr1 + arr2.reverse
=> [["3.1", 4], ["3.0", 7], ["1.9", 3], ["2.0", 6], ["2.1", 5]]