【发布时间】:2015-09-11 12:30:55
【问题描述】:
我正在尝试通过修改 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
【问题讨论】:
-
你不能创建一个模块的实例(一个模块没有new()方法),所以定义initialize()和实例变量是错误的。
-
我不认为我创建了模块的实例。模块名称为“总统”
标签: ruby