无法在ruby中打印出我的数组中的值

时间:2017-02-09 19:01:06

标签: arrays ruby variables printing instance

如何仅使用“Puts recipe.summary打印我的值?我已经在”说明“和”成分“中循环显示我的值,但是当我”放入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

2 个答案:

答案 0 :(得分:1)

Recipe对象没有sudo force vertical-align:middle !important or I'm coming for you方法,因为你没有注意你的嵌套:

summary

def ingredients @ingredients = ingredients.each do |ingredient| puts ingredient end def summary @summary puts "Name: #{name}" puts "#{ingredients}" end end 方法移到summary方法之外。

ingredients方法中的

@summary没有做任何事情,所以Ruby会抛弃它。

通过将Ruby与使用summary生成的方法名称混淆并从具有相同名称的方法内部调用它们来引发循环,例如:

attr_reader

运行该代码时,您将获得attr_reader :name, :instructions,:ingredients ... def instructions @instructions= instructions.each do |instruction| puts instruction end

我建议您编写有关编写Ruby代码的教程,使用自动处理缩进的编辑器,或者可以轻松地重新格式化/缩进,以及安装像Rubocop这样的代码分析器并虔诚地使用它。

答案 1 :(得分:0)

尝试返回@summary后,您正在调用DataArea = "Sheet21!" & Worksheets("Sheet21").Range("A3").CurrentRegion.Address(True, True, xlR1C1) 。 从技术上讲,puts的结果是返回的结果,这可能没什么 移动上方的puts "#{ingredients}"

puts