Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.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/4/wpf/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 - Fatal编程技术网

ruby代码中在何处定义变量的细微差别

ruby代码中在何处定义变量的细微差别,ruby,Ruby,我刚刚开始学习ruby,而变量的定义位置有点让我摸不着头脑。例如,此代码为什么工作: def two_sum(nums) result = nil i = 0 while i < nums.length k = (nums.length - 1) if nums[i] + nums[k] == 0 result = [i,k] end i += 1 k -= 1 end return result

我刚刚开始学习ruby,而变量的定义位置有点让我摸不着头脑。例如,此代码为什么工作:

def two_sum(nums)
  result = nil 
  i = 0   
  while i < nums.length 
    k = (nums.length - 1)
    if nums[i] + nums[k] == 0 
      result = [i,k]
    end 
    i += 1 
    k -= 1 
  end 
  return result 
end
def二和(nums)
结果=零
i=0
而我
为什么这个代码不起作用:

def two_sum(nums)
  result = nil 
  i = 0 
  k = (nums.length - 1)
  while i < nums.length 
    if nums[i] + nums[k] == 0 
      result = [i,k]
    end 
    i += 1 
    k -= 1 
  end 
  return result 
end
def二和(nums)
结果=零
i=0
k=(nums.length-1)
而我

提前谢谢你

我认为您的代码可能有一个bug

while i < nums.length 
  k = (nums.length - 1)
  ...
  k -= 1 # this statement has no effect!
end
如上所述,
k
的值在第一次迭代中从
(nums.length-1)
开始,然后在每次迭代中减少
1

亲蒂普-

在Ruby中,使用
for/while/until
循环是非常不寻常的。如果要在所有元素上循环,请使用
每个
每个_和_索引

array.each { |each| ... }
array.each_with_index { |each, n| ... }

如果你定义了“工作”和“不工作”对你意味着什么,这个问题将更容易回答。你期望得到什么结果?您看到了什么(错误、崩溃、意外值)?
array.each { |each| ... }
array.each_with_index { |each, n| ... }