Trip
Trip

Reputation: 27114

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"

Upvotes: 1

Views: 1464

Answers (2)

Toby Hede
Toby Hede

Reputation: 37133

Your value is a Hash, not an Array, so it doesn't have ordering or indexes, unless you are on Ruby 1.9

Upvotes: 0

cam
cam

Reputation: 14222

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?

Upvotes: 4

Related Questions