Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a chain of keys is existant in hashes

Tags:

ruby

I'm writing some ruby code that goes to the value of a hash of a hash of a hash....

amz_price_info.raw["Offers"]["Offer"]["OfferListing"]["Price"]["FormattedPrice"]

I want to access this code only when the structor of the code is available. Currently, my code is this:

    #amz_price_info.raw.class == Hashie::Mash
    price = if amz_price_info.raw["Offers"]
        if amz_price_info.raw["Offers"]["Offer"]
            if amz_price_info.raw["Offers"]["Offer"]["OfferListing"]
                if amz_price_info.raw["Offers"]["Offer"]["OfferListing"]["Price"]
                    if amz_price_info.raw["Offers"]["Offer"]["OfferListing"]["Price"]["FormattedPrice"]
                        amz_price_info.raw["Offers"]["Offer"]["OfferListing"]["Price"]["FormattedPrice"]
                    end
                end
            end
        end
    end

How do I refactor my code to be less verbose?

like image 982
Nick Silva Avatar asked Dec 06 '22 15:12

Nick Silva


1 Answers

This is one way if you do not want to define extra methods or introduce some libraries.

amz_price_info.raw
.fetch("Offers", {})
.fetch("Offer", {})
.fetch("OfferListing", {})
.fetch("Price", {})
.fetch("FormattedPrice", nil)
like image 117
sawa Avatar answered Dec 09 '22 04:12

sawa