In the following Ruby code, I have two methods d100_in_detectand d100_out_detectthat return Arrayunique elements (numbers for simplicity) contained aryin according to the result d100.
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
As you can see, the difference between the two methods is that in the first one it d100is called inside the block detect, while in the second 100 random numbers are stored in the numbersArray array and then used as it happens in d100_in_detect.
Suppose I call two methods as follows:
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
A typical output is as follows.
# 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 ]
I cannot understand why the two methods return such different results. Is there any implication when calling a method d100in a block detect?