ironsand ironsand - 2 months ago 10x
Ruby Question

How to update OpenStruct value with condition

How can I update values of

when a conditions is met?
I thought like this:

o = 1, b: 2)
o.each_pair{|k,v| v = 3 if v.even? }

But this code doesn't work.

I could update by this code, but it's quite hard to read.{|k,v| [k, v.even? ? 3 : v] }.to_h)

Is there better way to update
values by a condition?


Better but still not super clear:

o.to_h.each { |k, v| o[k] = 3 if v.even? }

EDIT - Better yet:

o.each_pair { |k, v| o[k] = 3 if v.even? }

This looks pretty good to me. You just can't mutate directly via the iterator.