0

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?

4
  • when i change the code to this puts "#{qDetails["message_stats"]}" it works but whole json would print Commented Mar 12, 2018 at 10:52
  • On what line do you get the error? Are you sure "message_stats" is always filled in, because that would explain immediately. Commented Mar 12, 2018 at 10:58
  • @nathanvda i want to get publish data so when i add ["publish"] i get that error. Commented Mar 12, 2018 at 11:02
  • @nathanvda message_stats not always filled. Commented Mar 12, 2018 at 11:02

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

@frodo why unaccept the answer then, and even more to accept a poor rephrasing of this one?
@Geoffroy it seems not fair indeed. I suggest you to flag the other copied answer, and explain precisely what happened.
(btw, the same user posted another copy-paste answer on a question of mine)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.