Ruby accessing constants from inner-class

烈酒焚心 提交于 2019-12-12 03:09:09

问题


I have a nested class like so:

class Mammal
    H = "Mammal"

    class Human
        H = "Human"
    end

end

And I want to make an Human object and after access the Human's constant, like so:

human = Mammal::Human.new # makes an object successfully

puts human::H             # does not work **
puts Mammal::Human::H     # works ["Human"]
puts Mammal::H            # works ["Mammal"]

**.. but it won't work ("..is not a class/module [TypeError]"). What am i doing wrong?


回答1:


What am I doing wrong?

You're trying to refer a constant from a wrong context. Constants are defined in class objects, not in instances. This works:

human = Mammal::Human.new
human.class.const_get(:H) # => "Human"



回答2:


Constants belong to classes, therefore constant resolution via the :: operator only works with class objects, not with instances of a class.

With that said, you can do this:

human.class::H

Object#class returns the object's class, relative to which you can resolve constants.



来源:https://stackoverflow.com/questions/14260931/ruby-accessing-constants-from-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!