Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested if else inside .each iteration

Tags:

ruby

nested

I'm wondering if this makes sense or if the syntax is wrong and basically if this is acceptable. I wanted to nest an if/else condition within my iteration of the array.

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

The array is a simple (binary) array and will only consist of 0s and 1s and I want to use the second array's elements as the indices of the first array that 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]
like image 206
Jeff Avatar asked Mar 16 '23 03:03

Jeff


1 Answers

If you don't want to use an if/else you can do:

second_array.each do |index|
  first_array[index] = (first_array[index] + 1) % 2
end
like image 108
Mischa Avatar answered Mar 24 '23 13:03

Mischa