Cameron Aziz
Cameron Aziz

Reputation: 487

How to access instance variables in arrays?

I have a gem that has an output with the following array (calling rate.inspect)

[#<Fedex::Rate:0x007f9552bd6200 @service_type="FEDEX_GROUND", @transit_time="TWO_DAYS", @rate_type="PAYOR_ACCOUNT_PACKAGE", @rate_zone="4", @total_billing_weight="8.0 LB", @total_freight_discounts={:currency=>"USD", :amount=>"0.0"}, @total_net_charge="18.92", @total_taxes="0.0", @total_net_freight="18.19", @total_surcharges="0.73", @total_base_charge="18.19", @total_net_fedex_charge=nil, @total_rebates="0.0">]

I can't seem to figure out what to call on rate to access the different values. I have tried rate.total_net_charge but I get:

undefined method `total_net_charge' for #<Array:0x007f955408caf0>

Advice?

Upvotes: 2

Views: 1126

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270617

It appears that the object you have inside rate is actually an Array with one element, a Fedex::Rate object. That is identifiable by the message:

undefined method `total_net_charge' for #<Array:0x007f955408caf0>

and much more subtly by the square brackets [] surrounding the <Fedex::Rate> object. So to drill in to retrieve total_net_charge, you would need to use an array method or index:

rate.first.total_net_charge

# Or by index
rate[0].total_net_charge

# Or assuming the array will sometimes have multiple objects
# loop or map to get them all
rate.each {|r| puts r.total_net_charge}

# or by map as an array of just the charges
rate.map(&:total_net_charge)

Upvotes: 6

Related Questions