質問

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 

http://ideone.com/bSkAXN

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top