Add parentheses:
@num.times {yield((rand*@limit).floor)}
Without the extra parentheses, yield(rand*@limit)
returns nil
, and you get a NoMethodError
for calling nil.floor
.
質問
I am practicing to code in Ruby and when I type the following code,I get the following error.In this case,what should I do?
The code is here:
class RandomSequence
def initialize(limit,num)
@limit,@num=limit,num
end
def each
@num.times {yield(rand*@limit).floor}
end
end
i=-1
RandomSequence.new(10,4).each do |num|
i=num if i<num
end
the error message I get is:
prog.rb:8:in block in each: undefined method floor for nil:NilClass (NoMethodError)
from prog.rb:8:in times
from prog.rb:8:in each
from prog.rb:14:in <main>
解決
Add parentheses:
@num.times {yield((rand*@limit).floor)}
Without the extra parentheses, yield(rand*@limit)
returns nil
, and you get a NoMethodError
for calling nil.floor
.