硬编码 Ruby Enumerable#reduce - 我有两种方法,但只有一种有效。为什么?
Hardcoding Ruby Enumerable#reduce - I have two methods, but only one works. Why?
我是新手,作为练习,我必须硬编码一个将数组作为参数的方法,如果该数组中的所有元素都为真,则 return 为真。如果不是,则为假。
def reduce_to_all_true(array)
array.each do |index|
if !index
return false
end
return true
end
end
如果任何元素为真,则此 return 为真...
同时,以下内容:
def reduce_to_all_true(array)
array.length.times { |index|
if !array[index]
return false
end }
return true
end
表现符合预期。我无法解决的问题是为什么?在我公认的有限理解中,它们是等效的解决方案。有人可以帮我理解这个吗?谢谢!
在第一种方法中,return true
位于 #each
循环内,因此它将只检查第一个元素,而 return 为真或假。在第二个中,它在循环之后,因此只有当循环完全完成而没有找到任何错误的元素时,它才会 return 为真。
def reduce_to_all_true(array)
array.each do |index| # each loop starts here
if !index
return false
end
return true # this will return true if the first element of array is true
end # and ends here
end
def reduce_to_all_true(array)
array.length.times { |index| # times loop starts here
if !array[index]
return false
end } #and ends here
return true #this will return true only if the times loop finishes
end
我是新手,作为练习,我必须硬编码一个将数组作为参数的方法,如果该数组中的所有元素都为真,则 return 为真。如果不是,则为假。
def reduce_to_all_true(array)
array.each do |index|
if !index
return false
end
return true
end
end
如果任何元素为真,则此 return 为真...
同时,以下内容:
def reduce_to_all_true(array)
array.length.times { |index|
if !array[index]
return false
end }
return true
end
表现符合预期。我无法解决的问题是为什么?在我公认的有限理解中,它们是等效的解决方案。有人可以帮我理解这个吗?谢谢!
在第一种方法中,return true
位于 #each
循环内,因此它将只检查第一个元素,而 return 为真或假。在第二个中,它在循环之后,因此只有当循环完全完成而没有找到任何错误的元素时,它才会 return 为真。
def reduce_to_all_true(array)
array.each do |index| # each loop starts here
if !index
return false
end
return true # this will return true if the first element of array is true
end # and ends here
end
def reduce_to_all_true(array)
array.length.times { |index| # times loop starts here
if !array[index]
return false
end } #and ends here
return true #this will return true only if the times loop finishes
end