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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With