Class Instance Variables in Ruby

Ever get confused between a variable held in an eigenclass and a class? Viz:

class Now
	def self.instance
		@greeting = "hello world"
	end
end

Now.instance # set up the greeting instance variable.

eigenclass = class << Now

end

# But where is @greeting stored?
puts Now.instance_variable_get("@greeting") # is it here?
puts eigenclass.instance_variable_get("@greeting") # or is it here?
  • Where is the instance method stored? Surely in the Eigenclass?
  • If so, then isn’t it naturally to think that the @greeting instance variable is also held there?

The answer

puts Now.instance_variable_get("@greeting") # is it here?
# => "hello world"

puts eigenclass.instance_variable_get("@greeting") # or is it here?
# =>
# Nope: it's not here

It looks like @greeting is stored in the Now class itself.

Written on April 6, 2025