Harish Shetty
Harish Shetty

Reputation: 64363

What is an elegant way to replace an element of an array based on a match criteria?

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

Answers (2)

thorncp
thorncp

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

vlabrecque
vlabrecque

Reputation: 346

array.map { |o| if condition(o) then obj else o }

maybe?

Upvotes: 6

Related Questions