Nested if else is inside.

I am wondering if this makes sense or the syntax is incorrect and, in principle, if it is acceptable. I would like to set an if / else condition within my array iteration.

def change_numbers(first_array, second_array)
  second_array.each do |index|

    if first_array[index] == 0
      first_array[index] = 1
    else
      first_array[index] = 0
    end

  end
end

An array is a simple (binary) array and will consist of only 0 and 1, and I want to use the second element of the array as indices of the first array, which I am going to change.

Example:

first_array = [0, 0, 0, 0, 1, 1, 1, 1, 1]
second_array = [3, 5, 7]

Result:

first_array = [0, 0, 0, 1, 1, 0, 1, 0, 1]
+4
source share
4 answers

If you do not want to use if / else, you can do:

second_array.each do |index|
  first_array[index] = (first_array[index] + 1) % 2
end
+2
source

A bitwise XOR :

ar = [0, 0, 0, 0, 1, 1, 1, 1, 1]
indices = [3, 5, 7]

indices.each{|i| ar[i] ^= 1 }
+2
source
def change_numbers(first_array, second_array)
  second_array.each { |index| first_array[index] = 1 - first_array[index] }
end
+2

-

def change_numbers(first_array, second_array)    
  second_array.each do |index| 
    first_array[index] = ((first_array[index] == 0) ? 1 : 0)
  end
end
+1

All Articles