What is an elegant way to replace an array element based on matching criteria?

I use the following logic to update a list item based on criteria.

def update_orders_list(order)
  @orders.delete_if{|o| o.id == order.id}
  @orders << order
end

Ideally, I would prefer the following approaches:

array.find_and_replace(obj) { |o| conditon }

OR

idx = array.find_index_of { |o| condition }
array[idx] = obj

Is there a better way?

+3
source share
2 answers

Starting from 1.8.7, Array # index takes a block. So your last example should work fine with a minor tweak.

idx = array.index { |o| condition }
array[idx] = obj
+5
source
array.map { |o| if condition(o) then obj else o }

may be?

+5
source

Source: https://habr.com/ru/post/1764937/


All Articles