Reputation: 1
I'm trying to access variables defined in class One
, through inheritance, in class Two
. I can't seem to find the right way of going about it - it seems to work for methods:
class One
class << self
def test
puts "I'm a method from class one"
end
end
end
end
And as a new object the variable is accessible:
class Two < One
test
end
#=> I'm a method from class one
class Test
attr_accessor :a
def initialize
@a = "hi"
end
end
Test.new.a
#=> "hi"
But I'm trying to do something like:
class One
class << self
a = "hi"
end
end
class Two < One
a
end
#=> NameError: undefined local variable or method `a' for Two:Class
For now I'm using class variables, but I'm sure there's a better way:
class One
@@a = "hi"
end
class Two < One
@@a
end
#=> "hi"
Upvotes: 0
Views: 170
Reputation: 36
Limosine is an example of a class inheriting, a variable (brand) and a method, to_s
class Car
def initialize(brand)
@brand = brand
end
def to_s
"(#@brand, #@model)"
end
end
class Limosine < Car
def initialize(brand, model)
super(brand)
@model = model
end
end
Use:
puts Merc.new("Mercedes", "Maybach")to_s
Upvotes: 0
Reputation: 118271
local and class instance variables wouldn't be accessible through inheritance in Ruby.
Upvotes: 1