如何从嵌套哈希中获取值

时间:2016-12-01 16:36:14

标签: ruby-on-rails ruby hash

我有这个嵌套哈希,有三个答案部分:

enter image description here

我想得到:

q2a.text= "Purchasing experience"  
q2a.answer="4"  
q2b.text= "Design on the product"  
q2b.answer="4"  
q2c.text="Quality of the product"  
q2c.answer="4"

但我不知道该怎么做。

{
            :question_text => "Please rate the following based on your overall experience:",
    :question_export_value => nil,
            :question_type => "10",
                   :answer => [
        [0] {
                    :answer_part => "Purchasing experience",
                  :answer_column => "4",
                    :answer_text => "4",
                   :answer_other => nil,
            :answer_export_value => nil,
                 :answer_comment => nil
        },
        [1] {
                    :answer_part => "Design on the product",
                  :answer_column => "4",
                    :answer_text => "4",
                   :answer_other => nil,
            :answer_export_value => nil,
                 :answer_comment => nil
        },
        [2] {
                    :answer_part => "Quality of the product",
                  :answer_column => "4",
                    :answer_text => "4",
                   :answer_other => nil,
            :answer_export_value => nil,
                 :answer_comment => nil
        }
    ],
           :question_score => "0",
            :question_code => nil,
          :question_number => "2"
}

1 个答案:

答案 0 :(得分:2)

很抱歉,但问题有点令人困惑,因为屏幕截图中的有效负载和您粘贴的代码根本不匹配。认为你想要学习一些带有哈希和数组的基本Ruby语法:

http://ruby-doc.org/core/Array.html

http://ruby-doc.org/core/Hash.html

具体检查[]方法。

我将尝试根据有效载荷做出回应。但基本上你正在处理散列,其中散列中的一个值是一个数组,而数组中的每个元素都是另一个散列。

所以,从主哈希开始你有类似的东西

answers = payload[:answer] # where payload is the hash you posted
q2a = answers[0]
q2b = answers[1]
q2c = answers[2]
puts q2a[:answer_part], q2a[:answer_text] # prints "Purchasing experience" and "4"
puts q2b[:answer_part], q2b[:answer_text] # prints "Design of the product" and "4"
puts q2c[:answer_part], q2c[:answer_text] # prints "Quality of the product" and "4"

总而言之,从哈希中使用密钥:answer获取数组,索引到所需数据的数组中,然后使用正确的密钥来获取数据。