如何在哈希中访问数组?

时间:2015-11-30 11:32:57

标签: ruby-on-rails arrays ruby hash

我在数组中有一个哈希:

values = {}
values.merge!(name => {
  "requested_amount" => @specific_last_pending_quota.requested_amount,
  "granted" => @specific_last_pending_quota.granted,
  "pending_final" => pending_final
})
@o_requests[request.receiving_organization][request.program_date][:data] = values

我将它发送到视图,然后当我得到它时:

= quota[:data].inspect
# {"theme"=>{"requested_amount"=>2, "granted"=>false, "pending_final"=>0}}

我想要获取这样的对象:

= quota[:data]["theme"].inspect

但是我收到了这个错误

can't convert String into Integer

2 个答案:

答案 0 :(得分:0)

尝试将其转换为正确的哈希我想它应该可以正常工作。

values = {}
 values.merge!(name => {:requested_amount => @specific_last_pending_quota.requested_amount, :granted => @specific_last_pending_quota.granted, :pending_final => pending_final})

@o_requests[request.receiving_organization][request.program_date][:data] = values

答案 1 :(得分:0)

我猜quota[:data]可能会返回哈希数组

尝试:

= quota[:data][0]["theme"]

在这里我尝试了获取相同错误的案例并检查:

 > h[:data]
 #=> [{"theme"=>{"requested_amount"=>2, "granted"=>false, "pending_final"=>0}}] 
 > h[:data]["theme"]
TypeError: no implicit conversion of String into Integer
    from (irb):10:in `[]'
    from (irb):10
    from /home/ggami/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
 > h[:data][0]["theme"]
 #=> {"requested_amount"=>2, "granted"=>false, "pending_final"=>0}