如何使用类中包含的模块访问类的实例变量?

时间:2015-06-25 04:29:17

标签: ruby

我试图通过修改班级FrancePresident中的年龄方法来输出" 59,bien sur"。我需要使用#{catchphrase}来做这件事。我尝试了很多方法,包括调用self.age。请参阅下面代码中的Rspec。

module Presidential
  attr_accessor :name, :age, :citizenship

  def initialize(name, age)
    @name, @age, @citizenship = name, age, self.class.citizenship
  end

end

class UnitedStatesPresident 
  include Presidential
   def self.citizenship
     "The United States of America"
   end
 end

class FrancePresident 
 include Presidential
 def name 
   name + ", #{catchphrase}"
 end
 def age
 end
 def citizenship
  "#{self.class.citizenship}, #{catchphrase}"
 end
 def self.citizenship
   "La France"
 end
 def catchphrase
   "bien sur"
 end
end

RSPEC
describe FrancePresident do
  describe "catchphrase" do
    it "sounds just right" do
      expect( FrancePresident.citizenship ).to eq("La France")
      sarcozy = FrancePresident.new("Nicolas Sarkozy", 59)
      expect( sarcozy.citizenship ).to eq("La France, bien sur")
      expect( sarcozy.age ).to eq("59, bien sur")
      expect( sarcozy.name ).to eq("Nicolas Sarkozy, bien sur")
    end
  end

  describe "inheritance" do
    it "should not inherit from President" do
      expect( FrancePresident.superclass.to_s ).not_to eq('President')
    end
  end
end

2 个答案:

答案 0 :(得分:1)

而且,这个:

 def name 
   name + ", #{catchphrase}"
 end

导致无限递归。 name()是getter,而name()是调用name()。在getter(和setter)中,您需要直接访问实例变量。

以下作品:

require 'rspec/autorun' 

module Presidential
  attr_accessor :name, :age, :citizenship

  def initialize(name, age)
    @name, @age, @citizenship = name, age, self.class.citizenship
  end
end



class UnitedStatesPresident 
  include Presidential

  def self.citizenship
    "The United States of America"
  end
end



class FrancePresident 
  include Presidential

  def name 
   "#{@name}, #{catchphrase}"
  end

  def age
    "#{@age}, #{catchphrase}"
  end

  def citizenship
    "#{self.class.citizenship}, #{catchphrase}"
  end

  def self.citizenship
    "La France"
  end

  def catchphrase
    "bien sur"
  end
end


RSpec.describe FrancePresident do
  describe "catchphrase" do
    it "sounds just right" do
      expect( FrancePresident.citizenship ).to eq("La France")
      sarcozy = FrancePresident.new("Nicolas Sarkozy", 59)
      expect( sarcozy.citizenship ).to eq("La France, bien sur")
      expect( sarcozy.age ).to eq("59, bien sur")
      expect( sarcozy.name ).to eq("Nicolas Sarkozy, bien sur")
    end
  end

  describe "inheritance" do
    it "should not inherit from President" do
      expect( FrancePresident.superclass.to_s ).not_to eq('President')
    end
  end
end

--output:--
$ ruby rspec_regular_ruby_code.rb 

Finished in 0.00159 seconds (files took 0.09554 seconds to load)
4 examples, 0 failures

答案 1 :(得分:0)

age方法改为喜欢这个,

def age
  "#{@age}, #{catchphrase}"
end