我正在尋找一種可與JavaScript的Array.prototype.every
方法媲美的方法,但使用紅寶石。在JavaScript中,它遍歷數組並返回true,如果每個元素都導致回調返回true。關於它的好處之一是,如果其中一個元素未能通過測試,它並不會在整個數組上迭代。相反,它會短路並返回錯誤。是否有與JavaScript的Array.prototype.every方法等價的ruby?
function isBigEnough(element) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); //=> false
[12, 54, 18, 130, 44].every(isBigEnough); //=> true
我知道我能得到與下級迭代器像while
環路類似的效果。
def isBigEnough(arr)
i = 0
result = true
while i < arr.length
if arr[i] >= 10
i++
else
i = arr.length
result = false
end
end
return result
end
is_big_enough([12, 5, 8, 130, 44]) #=> false
is_big_enough([12, 54, 18, 130, 44]) #=> true
但我想紅寶石會有這個東西。任何人都知道如何得到相同的效果?
嘗試['all?'](http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-all-3F)方法。 – orde
如果你downvote,請留下評論,解釋爲什麼 – williamcodes
我沒有downvote,但它不應該很難找出有人可能選擇downvote一個問題,可以通過簡單地瀏覽文檔或做一個快速的Google搜索。 –