更改对象数组Ruby中的一个属性

时间:2016-10-10 19:24:59

标签: arrays ruby

我正在写小程序,应该模拟烹饪。我有一系列成分的对象。每种成分都有数量和名称。我需要实施每次使用时减少配料量的方法。我有一个类厨房,其中的成分存储在一个阵列中。我是Ruby的新手,我真的不知道如何更改Array中单个对象的单个属性。这是我拥有的和不编译的内容:

def get_ingredient(name, count)
 totalIngredientsCount = @ingredients.inject(0){|count, p| count + p.count.to_f}

if (@ingredients.empty? == 0 || totalIngredientsCount == 0)
  puts("Kitchen is empty")
else
  {
      @ingredients.collect! { |i|
        if (i.name == name) then
          i.count = i.count - count #???
        else
          puts 'There is no ingredient with given name'
        end
      }
  }
end
end

class Ingredient
  def initialize(name, count)
    @name = name
    @count = count
  end

  attr_accessor :count
  attr_reader :name

end

1 个答案:

答案 0 :(得分:1)

我不确定你尝试了什么,但我建议你将你的问题分解成微小的谨慎集合,一次解决所述集合,然后最终将它们放在一起。

所以以你的问题为例,我会这样做:

    Problem 1: 
      - I have an array of objects which are ingredients. 
        - array_of_objects = []

      - Each ingredient has amount and name.
        - the fact that ingredients have an amount and name makes me think of a key value object. So use a hash maybe? 
        - one_ingredient = {}
          - I need a way to key track of an ingredient by name so add key name and set its value. 
             one_ingredient[:name] = "apple"
             one_ingredient[:amount] = 2

    - I need to put this ingredient into the array_of_objects
      - array_of_objects.push one_ingredient
         - this returns a data structure that looks like this: 
               [ {name: "apple, amount: 2} ]

你能看到发生了什么吗?接下来要做的是查看Ruby中的ArrayHash类,了解如何操作数据结构。想一想如何迭代Array和/或Hash

例如,让我们看一下Ruby Array课程中的each方法。如果单击该链接,您会看到可以通过调用每个数组来遍历数组,从而获得对数组中对象的访问权限。所以我们可以这样做:

    array_of_objects.each do |object|
     # each yields to a block and inside the block you have access 
     # to the object that has been yielded to each. Basically, if 
     # you use `pry` or debugger you can stop your code here, inspect
     # your object, and also see what methods you can call on your 
     # object. 

     # since your object is a hash, you should try calling `each` on 
     # it.  I believe Ruby Hashes have an each method - check to be    
     # sure. Then play around and see how you can access keys and 
     # values in a hash, and change their respective values.    
    end  

您可以从eacheach_with_key等简单方法开始。玩弄那些。

一旦你明白了,那么你就可以开始考虑构建一个将所有这些概念放在一起的class。如果你不能通过一个步骤思考,那么你可以尝试再次询问Stackoverflow但是非常具体(我知道当一个人不熟悉某种语言但是只是尝试描述你的问题时这很难用简单的英语)。

希望这会有所帮助。祝你好运:)