簡體   English   中英

如何訪問數組中的實例變量?

[英]How to access instance variables in arrays?

我有一個具有以下數組輸出的gem(調用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">]

我似乎無法弄清楚要調用什么rate才能訪問不同的值。 我已經嘗試過rate.total_net_charge但我得到:

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

建議嗎?

看來您擁有內部rate的對象實際上是一個帶有一個元素的Array ,即Fedex::Rate對象。 通過消息可以識別出:

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

並且更巧妙地用<Fedex::Rate>對象周圍的方括號[] 因此,要深入檢索total_net_charge ,您將需要使用數組方法或索引:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM