0

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" 

2 Answers 2

1

local and class instance variables wouldn't be accessible through inheritance in Ruby.

Sign up to request clarification or add additional context in comments.

3 Comments

exactly this. Instance variables belong to the instance, not the class. Only Class variables can be accessed, but they behave slightly different in that they exists across all Classes and derived classes, meaning if you overwrite them somewhere, you overwrite them for all Classes having access.
Ok, so using class variables (as in the final code excerpt) is the correct way of handling this situation? Why is it the case that class methods are accessible?
Because they are defined to be accessible. That's what they are there for. That's why they are called "class variables".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.