how to handle this array in ruby? -
there array this:
arr = [ {id: 1, status: 3}, {id: 2, status: 5}, {id: 3, status: 5}, {id: 4, status: 5}, {id: 5, status: 5}, ]
in array, if status of hash 3, change 2, , others change 1. if each hash status not 3, array not change.
i hope output should be:
arr = [ {id: 1, status: 2}, {id: 2, status: 1}, {id: 3, status: 1}, {id: 4, status: 1}, {id: 5, status: 1}, ]
if array this:
arr = [ {id: 1, status: 2}, {id: 2, status: 5}, {id: 3, status: 5}, {id: 4, status: 5}, {id: 5, status: 5}, ]
each hash status not 3, array doesn't change.
i can make this:
tmp = false arr.each |e| if e[:status].to_i == 3 e[:status] = 2 tmp = true break end end // note: if tmp == false, array not change if tmp == true arr.each |e| e[:status] = 1 if e[:status].to_i == 5 end end
but think bad idea, loop 2 times. has better solution? in advance!
most of answers submitted work correctly if first array element status: 3
.
you in single loop, if construct copy of array go, , swap original if found match
arr = [ {id: 1, status: 3}, {id: 2, status: 5}, {id: 3, status: 5}, {id: 4, status: 5}, {id: 5, status: 5}, ]; switch = false new_arr = array(arr.length) arr.each_with_index |e,i| if e[:status] == 3 new_elem = { id: e[:id], status: 3 } switch = true else new_elem = { id: e[:id], status: 1 } end new_arr[i] = new_elem end arr = new_arr if switch
so don't have iterate full array twice, construct unused copy array if there no status: 3.
i think might want consider using different data structure - maybe specific class models state changes you're using. maybe @ of state machine gems.
Comments
Post a Comment