Reputation: 64363
I am using the following logic to update a list item based on a criteria.
def update_orders_list(order)
@orders.delete_if{|o| o.id == order.id}
@orders << order
end
Ideally, I would have preferred these approaches:
array.find_and_replace(obj) { |o| conditon }
OR
idx = array.find_index_of { |o| condition }
array[idx] = obj
Is there a better way?
Upvotes: 4
Views: 7595
Reputation: 3627
As of 1.8.7, Array#index accepts a block. So your last example should work just fine with a minor tweak.
idx = array.index { |o| condition }
array[idx] = obj
Upvotes: 5