当我在编译器上运行以下关于方法和类的Ruby代码时,我遇到以下错误“第46行:未定义的局部变量或方法`app1'用于main:Object(NameError)”。提前谢谢:D !!
class Apps
def initialize(name)
@name = name
end
def add_app
"#{name} has been added to the App Center.Approval is pending!!"
end
def app_approved
"#{name} has been approved by the App Center"
end
def app_posted
"Congratulations!!!!#{name} has been posted to the App Store."
end
end
class Fbapps
def initialize(name)
@name = name
@apps = []
end
def add_new(a_app)
@apps << a_app
"#{@app} has been added to the #{@apps} store!!"
end
def weekly_release
@apps.each do |app|
puts @app
end
@apps.each do |app|
app.add_app
app.app_approved
app.app_posted
end
end
end
apps = ["Bitstrip", "Candy Crush" , "Instapaper"]
apps = Fbapps.new("Apps")
apps.add_new(app1)
apps.add_new(app2)
apps.add_new(app3)
puts apps.weekly_release
app1 = Apps.new("Bitstrip")
app2 = Apps.new("Candy Crush")
app3 = Apps.new("Instapaper")
答案 0 :(得分:1)
您需要先创建app1
,app2
和app3
,然后再将其添加到apps
:
apps = ["Bitstrip", "Candy Crush" , "Instapaper"]
app1 = Apps.new("Bitstrip")
app2 = Apps.new("Candy Crush")
app3 = Apps.new("Instapaper")
apps = Fbapps.new("Apps")
apps.add_new(app1)
apps.add_new(app2)
apps.add_new(app3)
puts apps.weekly_release
如上所述,您的类中还有其他错误,但如上所述更改执行顺序,它们应该相对简单。
更新:这是您的代码已更新以修复大部分错误:
class Apps
attr_accessor :name
def initialize(name)
@name = name
end
def add_app
"#{name} has been added to the App Center.Approval is pending!!"
end
def app_approved
"#{name} has been approved by the App Center"
end
def app_posted
"Congratulations!!!! #{name} has been posted to the App Store."
end
end
class Fbapps
attr_accessor :name
def initialize(name)
@name = name
@apps = []
end
def add_new(a_app)
@apps << a_app
"#{a_app.name} has been added to the #{self.name} store!!"
end
def weekly_release
@apps.each do |app|
puts app.name
end
@apps.each do |app|
puts app.add_app
puts app.app_approved
puts app.app_posted
end
end
end
答案 1 :(得分:1)
您在定义apps.add_new(app1)
之前尝试app1
。该行需要在 app1 = Apps.new("Bitstrap")
之后。