新手问题 元编程:这个貌似有个错误?

yolio2003 · April 29, 2014 · Last by yolio2003 replied at April 29, 2014 · 1742 hits

http://deathking.is-programmer.com/posts/29100.html

1.3.9 class_variables

如果你想知道一个类中有哪些类变量,我们可以使用 class_varibles 方法。他返回一个数组(Array),以符号(Symbol)的形式返回类变量的名称。

class Rubyist
  @@geek = "Ruby's Matz"
  @@country = "USA"
end

class Child < Rubyist
  @@city = "Nashville"
end
print Rubyist.class_variables # => [:@@geek, :@@country]
puts
p Child.class_variables # => [:@@city]

你可以从程序的输出中观察到 Child.class_variables 输出的是在 Child 类中定义的类变量(@@city)。Child 类没有从父类中继承类变量(@@geek, @@country)。

以上代码 我复制运行后

puts
  p Child.class_variables # => [:@@city, :@@geek, :@@country]

版本变了还是文章说错了?我的是

ruby -v
ruby 2.0.0p451 (2014-02-24) [x64-mingw32]

他应该是后面有个 false 参数表示不包括继承来的你没看见吧。

#1 楼 @alixiaomiao 多谢指点~,加了 (false) 参数可以了,原文确实没有加 (false) 参数呢!

You need to Sign in before reply, if you don't have an account, please Sign up first.