简体   繁体   中英

how to fetch values in hash array ruby

i have written small ruby code to get publish stats, code is following

begin
  response = conn.get("api/queues")
  statistics = JSON.parse(response.body)

  statistics.each do |qDetails|
    payload = "#{qDetails["name"]}"
    if payload != "aliveness-test"
      puts "#{qDetails["message_stats"]["publish"]}"          
    end             
  end      
rescue Faraday::Error::ConnectionFailed => e
  puts "Connection failed"
end

but i get this error in return

undefined method `[]' for nil:NilClass (NoMethodError)

message_stats json would be like this

{"deliver_get_details"=>{"rate"=>0.0}, "deliver_get"=>1357, "ack_details"=>{"rate"=>0.0}, "ack"=>1357, "redeliver_details"=>{"rate"=>0.0}, "redeliver"=>0, "deliver_no_ack_details"=>{"rate"=>0.0}, "deliver_no_ack"=>0, "deliver_details"=>{"rate"=>0.0}, "deliver"=>1357, "get_no_ack_details"=>{"rate"=>0.0}, "get_no_ack"=>0, "get_details"=>{"rate"=>0.0}, "get"=>0, "publish_details"=>{"rate"=>0.0}, "publish"=>1400}

what's the issue?

For ruby > 2.3, you can use dig :

qDetails.dig("message_stats", "publish")

This will safely access qDetails["message_stats"]["publish"]

The error you're getting is probably because qDetails["message_stats"] is nil, so calling [] on it doesn't work

You can use ruby-fetch method to get the data from hash where you are unsure about existence of a key. You can also set default value to return unlike dig returns nil if value not found

qDetails["message_stats"].fetch("publish", "default_value")

Another way would be like by using safe navigation operator ( & ):

qDetails["message_stats"]&.[]('publish') # Return nil if not found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM