其值为数组大小的哈希值

时间:2015-06-26 08:27:11

标签: arrays ruby hash

我需要一个方法来接受哈希并返回一个哈希,哈希的密钥来自旧哈希,值是旧哈希中数组的大小。即,

{ 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
# return
{ 1 => 3, 2 => 3, 7 => 2 }

有没有办法实现这个?

7 个答案:

答案 0 :(得分:12)

一种方式:

h = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }

h.merge(h) { |*_,a| a.size }
  #=> { 1 => 3, 2 => 3, 7 => 2 }

答案 1 :(得分:6)

您可以使用map构建新的[key, value]对数组,然后使用to_h将其转换为哈希值:

input = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
input.map { |key, value| [key, value.length] }.to_h

# => {1=>3, 2=>3, 7=>2}

答案 2 :(得分:2)

这非常简单:您可以使用inject逐个处理所有项目并撰写结果。

input = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
input.inject({}) do |result, (key, value)|
  result.merge(key => value.size)
end

# => {1=>3, 2=>3, 7=>2}

即使没有注入,只需使用.each循环所有项目并使用临时支持Hash构建结果。

答案 3 :(得分:2)

Just for the sake of completeness, a solution using each_with_object:

input = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }

input.each_with_object({}) { |(k, vs), h| h[k] = vs.size }
#=> {1=>3, 2=>3, 7=>2}

答案 4 :(得分:1)

一种方法是将预期的键和值插入新的哈希:

h = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
h2 = {}
h.each {|k, v| h2[k] = v.length}
h2
# => {1=>3, 2=>3, 7=>2}

答案 5 :(得分:1)

'import javax.swing.*;
 import java.awt.*;
 public class set_Components_where_i_want {
    public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setLayout(null);
        //make new Components 
        JButton b1 = new JButton("One");
        JButton b2 = new JButton("Two");
        JButton b3 = new JButton("Three");
        //add Components first
        frame.add(b1);
        frame.add(b2);
        frame.add(b3);
        //get frame inserts 
        Insets insets = frame.getInsets();
        Dimension size = b1.getPreferredSize();
        //set position here
        b1.setBounds(50 + insets.left, 10 + insets.top,
                 size.width, size.height);
        size = b2.getPreferredSize();
        b2.setBounds(110 + insets.left, 80 + insets.top,
                 size.width, size.height);
        size = b3.getPreferredSize();
        b3.setBounds(300 + insets.left, 60 + insets.top,
                 size.width + 100, size.height + 40);
        //set size for the frame so it can contain all Components
        frame.setSize(600 + insets.left + insets.right,
                  250 + insets.top + insets.bottom);
        // make the frame be visible
        frame.setVisible(true);
}

答案 6 :(得分:0)

或者你可以试试这个,

h = { 1 => [1,1,1], 2 => [3,4,5], 7 => [9,12] }
Hash[h.map {|key, value| [key, value.length]}]
#  => {1=>3, 2=>3, 7=>2}