2017-02-09 31 views
-1

我如何打印出我的价值只使用“放置recipe.summary”循环通过他们在“说明”和“成分”,但没有显示当我“放置食谱。摘要”。不能打印出我的阵列中的值在红宝石

也许我通过它错误地循环? 这里是我的代码。

class Ingredient 
    attr_reader :quantity, :unit, :name, :summary 
    def initialize (quantity,unit,name) 
    @quantity = quantity 
    @unit = unit 
    @name = name 
    @summary= summary 
    end 

    def summary 
    "#{quantity} #{unit} #{name}" 
    end 
end 




class Recipe 
    attr_reader :name, :instructions,:ingredients 

    def initialize(name,instructions,ingredient) 
    @name = name 
    @instructions = instructions 
    @ingredient = ingredient 
    end 

    def instructions 
@instructions= instructions.each do |instruction| 
    puts instruction 
    end 
end 

    def ingredients 

    @ingredients = ingredients.each do |ingredient| 
     puts ingredient 
    end 


    def summary 
    @summary 
    puts "Name: #{name}" 
    puts "#{ingredients}" 
    end 
end 
end 

# ingredient = Ingredient.new(47.0, "lb(s)", "Brussels Sprouts") 
# puts ingredient.summary 

name = "Roasted Brussels Sprouts" 

instructions = [ 
    "Preheat oven to 400 degrees F.", 
    "Cut off the brown ends of the Brussels sprouts.", 
    "Pull off any yellow outer leaves.", 
    "Mix them in a bowl with the olive oil, salt and pepper.", 
    "Pour them on a sheet pan and roast for 35 to 40 minutes.", 
    "They should be until crisp on the outside and tender on the inside.", 
    "Shake the pan from time to time to brown the sprouts evenly.", 
    "Sprinkle with more kosher salt (I like these salty like French fries).", 
    "Serve and enjoy!" 
] 

ingredients = [ 
    Ingredient.new(1.5, "lb(s)", "Brussels sprouts"), 
    Ingredient.new(3.0, "tbspn(s)", "Good olive oil"), 
    Ingredient.new(0.75, "tspn(s)", "Kosher salt"), 
    Ingredient.new(0.5, "tspn(s)", "Freshly ground black pepper") 
] 


recipe = Recipe.new(name, instructions, ingredients) 
puts recipe.summary 
+0

请阅读“[mcve]”。尝试将您的代码降至最低程度,以避免重复出现问题。 –

回答

0

你试图返回@summary后调用puts。 技术上则返回puts "#{ingredients}"的结果是什么,这可能没什么。
上面移动puts

def summary 
    puts "Name: #{name}" 
    puts "#{ingredients}" 
    @summary 
end 
+0

之后它仍然不打印任何东西,但我明白你的意思。 – Tiago

1

的配方对象没有一个summary方法,因为你没有注意你嵌套:

def ingredients 

    @ingredients = ingredients.each do |ingredient| 
     puts ingredient 
    end 


    def summary 
    @summary 
    puts "Name: #{name}" 
    puts "#{ingredients}" 
    end 
end 

移动summary方法ingredients法外。

@summary里面的summary方法不会做任何事情,Ruby会把它扔掉。

attr_reader :name, :instructions,:ingredients 

... 

    def instructions 
    @instructions= instructions.each do |instruction| 
    puts instruction 
    end 

运行的代码时,你会得到SystemStackError: stack level too deep

你用了与attr_reader生成的方法名称混淆Ruby和从内部方法具有相同的名称,如称他们造成循环。

我建议通过编写Ruby代码的教程,使用自动处理缩进或使重新格式化/缩进容易的编辑器,以及安装像Rubocop这样的代码分析器并使用它进行虔诚使用。