由子元素的Ruby排序数组

时间:2016-02-27 10:59:28

标签: arrays ruby

我有一个“数组数组”,一次包含两个值。

array = [[:tuesday, 0.25], [:monday, 1], [:thursday, 0.75]]

我想使用“child”数组中的数字按降序对“父”数组进行排序。结果如下:

array = [[:monday, 1], [:thursday, 0.75], [:tuesday, 0.25]]

我不太确定从哪里开始。

4 个答案:

答案 0 :(得分:6)

您可以将块传递给sort方法,如下所示:

array.sort { |a, b| b[1] <=> a[1] }

答案 1 :(得分:4)

我倾向于写

array.sort_by(&:last).reverse

答案 2 :(得分:2)

array = [['Tuesday',0.25],['Monday',1],['Thursday',0.75]]
p array.sort_by{|a| -a[1]}
# => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]]

答案 3 :(得分:1)

您可以使用new_array返回新的排序数组(保存为new_array = array.sort{|x, y| y[1] <=> x[1]} # => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]] )。

array

这使原始array # => [["Tuesday", 0.25], ["Monday", 1], ["Thursday", 0.75]] 保持不变。

sort!

或者您使用array.sort!{|x, y| y[1] <=> x[1]} # => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]] array # => [["Monday", 1], ["Thursday", 0.75], ["Tuesday", 0.25]] 更改原始数组的顺序。

package com.developer.sven.dartworkout20;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;

import java.util.ArrayList;

public class PreferenceDartThrow extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.preference_dart_throw_page);

    Intent preferenceDartThrowPageOpened = getIntent();
    String previousActivity = preferenceDartThrowPageOpened.getExtras().getString("Pref");
}

ArrayList<Integer> selection = new ArrayList<Integer>();

public void selectNumber(View view) {
    boolean numberChecked = ((CheckBox) view).isChecked();
    switch (view.getId()) {
        case R.id.number_D1:
            if (numberChecked) {
                selection.add(1);
            } else {
                selection.remove(1);
            }
            break;

        case R.id.number_D2:
            if (numberChecked) {
                selection.add(2);
            } else {
                selection.remove(2);
            }
            break;

        case R.id.number_D3:
            if (numberChecked) {
                selection.add(3);
            } else {
                selection.remove(3);
            }
            break;

        case R.id.number_D4:
            if (numberChecked) {
                selection.add(4);
            } else {
                selection.remove(4);
            }
            break;

        case R.id.number_D5:
            if (numberChecked) {
                selection.add(5);
            } else {
                selection.remove(5);
            }
            break;
  }
}
}