ruby代码中在何处定义变量的细微差别
我刚刚开始学习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
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| ... }