Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
Harish Shetty Avatar asked Sep 15 '25 05:09

Harish Shetty


2 Answers

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

maybe?

like image 177
vlabrecque Avatar answered Sep 17 '25 18:09

vlabrecque


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
like image 22
thorncp Avatar answered Sep 17 '25 20:09

thorncp