A question about constant search in Ruby. In the code below,
class M CONST = "Hello, world" end class M def self.say CONST end end p M.say # "Helo, world"
Why is this standard output possible?
The constant search of Ruby will look back at "1: Lexical scope" and then go back up "2: Inheritance chain".
Constant CONST is not defined in the lexical scope where the standard output method is defined. (The M class is defined twice, but the first definition and redefinition recognize it as a different "lexical scope".)
Also, the method defined in the M class is a singular method, and I think it will be a method belonging to
#, which is a metaclass (?) of M, not the M class itself. The
#and M class have a "class-object" relationship, but not a "super class-child class" relationship, so
#cannot be used to refer to the constant CONST defined in the M class.
Therefore, you shouldn't be able to find a constant that doesn't exist in either "lexical scope" or "superclass".
I think it is
... but I can actually refer to it, so I think that either way of thinking (recognition of lexical scope or singular class and singular method) is wrong. I'm sorry, but I'm not sure which one is wrong or whether there is another serious misunderstanding.
Can you tell me which way of thinking is wrong?
Answer # 1
In the second
class M, the environment of
CONSTis already defined I don't think it's unnatural if you think you are inside.
- ruby - i want to know the reason for implementing it in a class method or module when solving an exercise
- ruby - [rails] the class attribute specified by the div tag enclosed in simple_format is not applied
- ruby - why can't the default image be referenced on the front side when using carrierwave with the rails api?
- ruby - + becomes nil class
- ruby on rails - i want to add a class to link_to
- ruby - i want to define a human class
- ruby - [bootstrap] even if card-img-top is added to class, the image is not placed at the top
- ruby on rails - how to test that a specific element has a class name using rspec/capybara
- ruby on rails 6 - class does not end with end
- ruby - i don't know where to write class in select tag
- ruby - i learned about singular methods, but do you really have a chance to use them?
- i don't know ruby class name new(:symbol)
- ruby on rails i created the controller name in singular form instead of plural form and worked on it