How can I find the index of the last item in an array?
My Array:
(rdb:381) pp params[:payments]
{"0"=>{":amount_paid"=>"100.00", ":date_paid"=>"2/27/2008"},
"1"=>{":amount_paid"=>"80.00", ":date_paid"=>"3/27/2008"},
"2"=>{":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}}
I don't believe this is an object . Performing params[:payments].last
returns this :
NoMethodError Exception: undefined method `last' for开发者_开发技巧 #<ActiveSupport::HashWithIndifferentAccess:0x1065e8448>
I am trying to find the index of that last item. In this case, the answer is 2, or "2"
Hey, your array is actually a hash. You could maybe get the index of the last key by doing something like params[:payments].keys.map(&:to_i).max.to_s
It would be even better to pass an actual array back. How are you generated the :payments
option?
Your value is a Hash, not an Array, so it doesn't have ordering or indexes, unless you are on Ruby 1.9
精彩评论