读书人

ruby 运行报错 uninitialized constan

发布时间: 2013-01-25 15:55:29 作者: rapoo

ruby 运行报错 uninitialized constant Sequence (NameError)。
看着《The Ruby Programing》这本书的例子自己写了2个类。
Sequence.rb


#
#this class represents a sequence of numbers characterized by the three
#parameters from, to, and by. The numbers x in the sequence obey the
#following two constraints:
#
# from <= x <= to
# x = from + n*by, where n is aninteger
#
class Sequence
#This is an enumerable class; it defines an each iterator below.
#initialize newly created instances of the class
def initialize(from, to, by)
#Just save our paramerters into instance variables for later use
@from, @to, @by = from, to, by #Note parallel assignmendt and @ prefix
end

#this is the iterator required by the Enumerable module
def each
x = @from #Start at the starting point
while x <= @to #while we haven't reached the end
yield x #pass x to rhe block associated with the iterator
x += @by #Increment x
end
end

#Define the length method (following arrarys) to return hte numgber of
#values in the sequence
def length
return 0 if @from > @to
Integet((@to - @from)/@by) + 1
end

#Define another name for the same method
#It is common for methods to have multiple names in Ruby
alias size length #size is now a synonym for length
#Override the array-access operator give random accesss to give random access to the sequence
def[](index)
return nil if index < 0 #Return nul for negative indexes
v = @from + index*@by #compute the value
if v <= @to #if it is part of the sequence
v #return it
else #otherwise
nil
end
end

#Override arichmetic operators to return new Squence objects


def *(factor)
Squence.new(@from*factor, @to*facotor, @by*factor)
end

def +(offset)
Squence.new(@from + offset, @to + offset, @by)
end
end



Hello.rb

s = Sequence.new(1, 10, 2) #from 1 to 10 by 2's
s.each {|x| print x}
print s[s.size - 1]
t = (s+1)*2




我使用的编译器是Apatana
两个类都是在一个目录下面的。
我是初学者使用ruby,请问是哪里出错了呢?谢谢!
[解决办法]
require "sequence"

是请求这个文件,

Sequence.rb #前面字母小写

读书人网 >Ruby Rails

热点推荐