在下面的Ruby代碼紅寶石#detect行爲我有根據的d100
結果包含在ary
兩種方法d100_in_detect
和d100_out_detect
其中(爲簡單起見數字)返回唯一元素的Array
。利用隨機數
def d100
1 + (rand 100)
end
def d100_in_detect(ary)
choice = [ ]
100.times do
choice.push ary.detect { |el| d100 <= el }
end
choice.uniq.sort
end
def d100_out_detect(ary)
choice = [ ]
numbers = [ ]
100.times do
numbers.push d100
end
numbers.each do |i|
choice.push ary.detect { |el| i <= el }
end
choice.uniq.sort
end
正如你可以看到這兩種方法之間的差別在於,在所述第一d100
稱爲detect
的塊內,而在第二個100個隨機號碼存儲在numbers
陣列,然後被用作它發生在d100_in_detect
。
讓我們假設我所說的兩個方法如下
ary = [ ]
50.times do |i|
ary.push i * 5
end
puts '# IN DETECT #'
print d100_in_detect ary
puts
puts '# OUT DETECT #'
puts d100_out_detect ary
puts
一個典型的輸出如下。
# IN DETECT #
[ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 ]
# OUT DETECT #
[ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 ]
我找不出爲什麼這兩個方法返回這種不同的結果。 在detect
的區塊中調用d100
方法是否有任何含義?
感謝在塊_each號,您執行D100 again_。 – dave
是的,這真的是它的關鍵。我放下了其餘的部分,因爲我必須運行並使用腳本來了解發生了什麼。感謝您提供這樣一個詳細的問題! –