Reputation: 1789
Suppose a simple ruby program about CONSTANT variable:
OUTER_CONST = 99
class Const
def get_const
CONST
end
CONST = OUTER_CONST + 1
end
puts Const.new.get_const
I assume the result of Const.new.get_const
should be nil, but the result is 100! I wonder why?
Upvotes: 1
Views: 102
Reputation: 8507
get_const
is a method, and you are calling it after CONST
definition; so when you call it CONST
is already defined.
def get_const ... end
defines a method, does not execute its content; you execute its content when you call it at the Const.new.get_const
line, so when CONST
is already defined.
Besides: if CONST
was not defined at the moment of get_const
call, you would not get nil
, but a NameError
:
class Const
def get_const
CONST
end
end
Const.new.get_const #=> NameError: uninitialized constant Const::CONST
Upvotes: 4
Reputation: 33626
This is because Ruby is dynamic and the constant lookup happens at runtime. Also keep in mind that your script is evaluated sequentially (ie. line by line).
I've added some comments for clarity:
OUTER_CONST = 99
class Const
def get_const
CONST
end
CONST = OUTER_CONST + 1
# the CONST constant is now
# defined and has the value 100
end
# at this point the Const class
# and CONST constant are defined and can be used
# here you are calling the `get_const` method
# which asks for the value of `CONST` so the
# constant lookup procedure will now start and
# will correctly pick up the current value of `CONST`
Const.new.get_const # => 100
Upvotes: 2