ironsand ironsand - 3 months ago 15
Ruby Question

How to update OpenStruct value with condition

How can I update values of

OpenStruct
when a conditions is met?
I thought like this:

o = OpenStruct.new(a: 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.

OpenStruct.new(o.each_pair.map{|k,v| [k, v.even? ? 3 : v] }.to_h)


Is there better way to update
OpenStruct
values by a condition?

Answer

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.

Comments