There is an array like this:
arr = [
{id: 1, status: 3},
{id: 2, status: 5},
{id: 3, status: 5},
{id: 4, status: 5},
{id: 5, status: 5},
]
In this array, if status of any hash is 3, it will be change to be 2, and others will change to be 1. if each hash status is not 3, the array does not change.
I hope the 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 the array like 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 is not 3, so the array doesn't change.
I can make it like this:
tmp = false
arr.each do |e|
if e[:status].to_i == 3
e[:status] = 2
tmp = true
break
end
end
// note: if tmp == false, the array does not change
if tmp == true
arr.each do |e|
e[:status] = 1 if e[:status].to_i == 5
end
end
But I think it is a bad idea, it will loop two times. Anyone has the better solution? Thanks in advance!