0

I have the following JSON stored in the structure field. I want to check if the key structure[cluster][ID] exists with ruby within a ternary operator.

{
        "ID": "client DEF",
        "cluster": {
            "ID": "cluster 789",
            "flights": 4,
            "profit": 5245,
            "clv": 2364
        },
        "segment": {
            "ID": "segment 876",
            "flights": 2,
            "profit": 2150,
            "clv": 1564
        },
        "node": {
            "xpos": 1,
            "ypos": 2
        }
    }

Example

structure.has_key?(cluster.ID) ? structure["newField"] = "true" :structure["newField"] = "false"

Root level attributes work well with has_key? - I am not able to check exists on a nested level element. Any help is appreciated.

1 Answer 1

1

I'd suggest using the hash #dig method which lets you safely navigate levels of the hash. Also, instead of using a ternary, just assign the true/false value of the presence of the tested value to the newField, converted to a string if that better suits...

structure['newField'] = structure.dig(:cluster, :id).present?.to_s
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I am using a older version of ruby which do not have .present?. Is there a different method i can use? will has_key? work?
I was able to use .nil? and get through this. Thanks
present? is part of ActiveSupport (and thus Rails) and has been around a VERY long time.

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.