views:

45

answers:

2

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?

+4  A: 
array.map { |o| if condition(o) then obj else o }

maybe?

vlabrecque
Yep this should do it. Though `condition(o) ? obj : o` might be a little more standard. You could even extend the `Array` class with a `find_and_replace` method to make it work just like your psuedo code.
Squeegy
maybe map! to make it in-place?
tokland
I don't want reconstruct the array. Just want to replace the index.
KandadaBoggu
+1  A: 

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
thorncp
I didn't find this in Array documentation as I was looking at 1.8.6 documentation. Thanks.
KandadaBoggu