【发布时间】:2014-04-16 01:41:30
【问题描述】:
你有一个数组。如果数组中任意两个数字加到零,则返回true。有多少对并不重要——只要有一对加到零,就返回true。如果有一个零,它只能返回true,如果有多个。
我写了两个函数,一个用于检查每个函数,最后一个将两者结合起来,如果其中一个不满足,则返回false。
def checkZero(array)
zerocount = 0
for j in 0..array.count
if array[j] == 0
zerocount += 1
end
end
if zerocount > 1 #this part seems to not be working, not sure why
return true
else
return false
end
end
def checkNegative(array)
for j in 0..array.count
neg = -array[j] #set a negative value of the current value
if array.include?(neg) #check to see whether the negative exists in the array
return true
else
return false
end
end
end
def checkArray(array)
if checkZero(array) == true or checkNegative(array) == true
return true
else
return false
end
end
然后运行类似
array = [1,2,3,4,0,1,-1]
checkArray(array)
到目前为止,Ruby 没有返回任何内容。我只是得到一个空白。我感觉我的return 不对。
【问题讨论】:
-
一方面,不要在 Ruby 中使用
for。只需使用each—for字面意思就是调用each,所以它是单一的间接方式。此外,在checkZero和checkArray中,您可以只将最后一条语句作为条件语句,无需if。此外,带下划线的方法名称更传统(例如check_array而不是checkArray)。最后,请注意and/oris not the same as&&/||in Ruby;当布尔逻辑是意图时,只能使用后者。 -
哦,我无法重现您的问题,
checkArray([1,2,3,4,0,1,-1])返回true就好了。 -
@AndrewMarshall 感谢您的提示。将阅读 and/or 和 && || 之间的区别。