嵌套if else else .each iteration

时间:2015-05-09 17:20:08

标签: ruby nested

我想知道这是否有意义或语法是否错误,基本上如果这是可以接受的。我想在我的数组迭代中嵌入一个if / else条件。

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

数组是一个简单的(二进制)数组,只包含0和1,我想使用第二个数组的元素作为我要改变的第一个数组的索引。

示例:

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

结果:

first_array = [0, 0, 0, 1, 1, 0, 1, 0, 1]

4 个答案:

答案 0 :(得分:2)

如果你不想使用if / else,你可以这样做:

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

答案 1 :(得分:2)

A bit-wise XOR

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

indices.each{|i| ar[i] ^= 1 }

答案 2 :(得分:2)

def change_numbers(first_array, second_array)
  second_array.each { |index| first_array[index] = 1 - first_array[index] }
end

答案 3 :(得分:1)

你可以试试这个 -

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