-3

コンパイラでメソッドとクラスに関する次の Ruby コードを実行すると、「Line 46: undefined local variable or method `app1' for main:Object (NameError)」というエラーが発生します。

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")
4

2 に答える 2

1

に追加する前に、、、app1およびapp2を作成する必要があります。app3apps

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
于 2013-11-13T21:12:35.893 に答える
1

apps.add_new(app1)を定義する前にやろうとしていますapp1その行は の後 に行く必要がありますapp1 = Apps.new("Bitstrap")

于 2013-11-13T21:13:10.483 に答える