简体   繁体   中英

Ruby method and variable inheritance

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" 

本地和类实例变量将无法通过Ruby中的继承进行访问。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM