Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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 迭代固定数组_Ruby_Arrays_Loops_Bits - Fatal编程技术网

Ruby 迭代固定数组

Ruby 迭代固定数组,ruby,arrays,loops,bits,Ruby,Arrays,Loops,Bits,我有一个19位长的数组(array1),初始化为0,还有一个64位长的数组(clave)。我想迭代array164次,同时还检查了clave。我这样做: def fase2 j=0 for i in 0..63 @array1[j]=@array1[18].to_i^@array1[17].to_i^@array1[16].to_i^@array1[13].to_i^@clave[i].to_i j=j+1 if j>19

我有一个19位长的数组(
array1
),初始化为
0
,还有一个64位长的数组(
clave
)。我想迭代
array1
64次,同时还检查了
clave
。我这样做:

def fase2
    j=0
    for i in 0..63
        @array1[j]=@array1[18].to_i^@array1[17].to_i^@array1[16].to_i^@array1[13].to_i^@clave[i].to_i
    j=j+1
    if j>19  
        j=0  
    end  
    end
    print @array1
    gets
end

有没有更干净的方法来做到这一点…?

我可以想出一些改进

  • 将所有变量名称为更有意义的名称。
    @array1
    中有什么?整数?考虑调用它<代码> @ int ts /代码>。用复数来称呼数组是件好事。如果可能的话,
    j
    i
    也是如此

  • 使用
    (0..63)。每个都对0..63中的i执行| i |
    ,而不是
    。更像红宝石

  • 在运算符之间使用间距,尤其是相等运算符<代码>j=0
    j=0

  • 小条件可以放在一行:
    j=0,如果j>19

  • 为什么是神奇的数字?为什么18、17、16和13是特别的?将它们放入一个适当命名的数组中开始,然后像这样使用array#reduce

    special_indeces = [18, 17, 16, 13]
    
    ... and then in loop ...
    
    xor = special_indeces.reduce do |val, index|
      val ^ @array1[index].to_i
    end
    
  • 在最后得到了什么?这有什么意义

  • 祝你好运,这段代码需要认真研究

    这是未经测试的,但更多的是如何编写内部循环:

    def fase2
      @clave.each do |clave|
        (0..19).each do |j|
          @array1[j] = @array1[18].to_i ^ @array1[17].to_i ^ @array1[16].to_i ^ @array1[13].to_i ^ clave.to_i
        end
      end
      print @array1
      gets
    end