初学ruby
在看到ruby的<=>这个运算符的调用上有些疑惑,希望各位能解答一下
class Person
  def initialize(name,age)
    @name = name
    @age = age
  end
  def <=>(other)
    self.age <=> other.age
  end
end
test1 = Person.new("test1", 20)

test2 = Person.new("test2", 18)

test1.<=>(test2)

上面的<=>应该是定义的方法名吧,我理解的other这个参数是Person类的另一个实例化对象吧
但是我自己定义了两个实例化对象test1和test2
调用test1的<=>方法并把test2这个实例化对象传进去,为什么程序总报<=>:undefine method 'age'
for #.......这个错误呢?
刚开始学,可能很多是概念上的错误,希望能帮我解答一下,谢谢
评论
darkhucx 2007-03-06
谢谢透明,呵呵,解决了,哦 明白了,ruby方法中的变量在类外部是无法直接访问的,设置age属性为只读,其实是调用Module模块的方法来实现在类外访问,呵呵,谢谢楼上两位,尤其是透明!
刑天战士 2007-03-06
all instant field in ruby is not visible for others but itself, you should define a method whose name is the same as the field name.
gigix 2007-03-06
attr_reader :age
darkhucx
  • 浏览: 12832 次
  • 性别: Icon_minigender_1
  • 来自: 宁夏银川
  • 详细资料
搜索本博客
我的相册
22a41ef8-e718-43bc-a16e-da7d6daa1200-thumb
rails工作原理
共 1 张
最近加入圈子
最新评论
评论排行榜