Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 嵌套的if-else。每个迭代_Ruby_Nested - Fatal编程技术网

Ruby 嵌套的if-else。每个迭代

Ruby 嵌套的if-else。每个迭代,ruby,nested,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 该

我想知道这是否有意义,或者语法是否错误,基本上是否可以接受。我想在数组的迭代中嵌套一个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]
你可以试试这个-

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

如果您不想使用If/else,可以执行以下操作:

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


虽然您可能想检查
first\u数组
中的索引是否存在,但我看不出这有什么问题。假设它已定义,这是一种可以接受的方法吗?或者,除了做我想做的事情,还有其他选择吗。对不起,我现在只是在学习基础知识,非常感谢你的帮助!我相信还有其他不涉及if/else的方法,但这是一种可以接受的方法。谢谢!!我从来不会这样做,但这真的很有帮助!!或者
(第一个数组[index]-1)。abs
是的,这就是我要找的操作符。@steenslag,你能解释一下吗,或者把我和文档联系起来吗?这看起来是一个很酷的概念,我想进一步理解它。我在google上尝试了前几个链接,但只是一些我无法理解的例子。@Jeff,它是在Fixnum类上定义的,但是文档没有帮助。用1进行异或运算是一种众所周知的位翻转技术;添加了维基百科的链接。另一种变通方法,从来没有这样想过。谢谢你的洞察力!
ar = [0, 0, 0, 0, 1, 1, 1, 1, 1]
indices = [3, 5, 7]

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