2017-02-09 11 views
-1

Как распечатать мои значения, используя только «Направляет recipe.summary? Ive через них в« инструкциях »и« ингредиентах », но ни один из них не показывает, когда я« Накладывает рецепт ». резюме».Невозможно распечатать значения из моего массива в рубине

Может быть, им перекручивание через это неправильно? Вот мой код.

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

Вы звоните puts после попытки вернуть @summary. Технически результатом 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 и называя их внутри методов с одинаковыми именами, такие как:

attr_reader :name, :instructions,:ingredients 

... 

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

Вы получите SystemStackError: stack level too deep при выполнении этого кода.

Я бы рекомендовал работать с учебниками по написанию кода Ruby с помощью редактора, который автоматически обрабатывает отступы или упрощает переформатирование/отступ и установку анализатора кода, такого как Rubocop, и использования его религиозно.