在ruby中迭代多维哈希

时间:2017-01-22 20:39:44

标签: ruby

  groceries=[{"bread"=>"2", "eggs"=>"3", "cheese"=>"1", "butter"=>"4"},
             {"juice"=>"3", "milk"=>"1", "tea"=>"1", "sugar"=>"1"}] 

如何迭代每个哈希并推入单独的数组?  我想要一些看起来像这样的东西:

 items = [["bread","eggs","cheese","butter"],["juice","milk","tea","sugar"]] 

2 个答案:

答案 0 :(得分:2)

试试这个

class Player2 {
    // make health a "bound property" by using property change support and listeners
    public static final String HEALTH = "health";
    public static final int MAX_HEALTH = 800;
    private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(this);
    private int health;

    public Player2() {
        this.health = MAX_HEALTH;
    }

    public int getHealth() {
        return health;
    }

    // notify all listeners if health changes
    public void setHealth(int health) {
        int oldValue = this.health;
        int newValue = health;
        this.health = health;
        pcSupport.firePropertyChange(HEALTH, oldValue, newValue);
    }

    // allow outside code to listen for changes to all bound properties
    // should also have the associated remove listener methods too
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        pcSupport.addPropertyChangeListener(listener);
    }

    public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
        pcSupport.addPropertyChangeListener(name, listener);
    }

}

答案 1 :(得分:1)

如果您只想要包含5个或更多字符的键:

p groceries.map{ |hash| hash.keys.select{ |key| key.length >= 5 } }
#=> [["bread", "cheese", "butter"], ["juice", "sugar"]]

如果您只想要最多2个包含5个或更多字符的键:

p groceries.map{ |hash| hash.keys.select{ |key| key.length >= 5 }.first(2) }
#=> [["bread", "cheese"], ["juice", "sugar"]]