2016-10-10 11 views
-3

私は料理をシミュレートするはずの小さなプログラムを書いています。私は成分であるオブジェクトの配列を持っています。各成分には量と名前があります。私はそれが使用されるたびに成分の量を減らす方法を実装する必要があります。私は、成分がアレイに保管されるクラスKitchenを持っています。私はRubyの新機能ですが、Array内の単一のオブジェクトの単一のプロパティを変更する方法がわかりません。ここに私が持っていると何をコンパイルできないものです:オブジェクトの配列のプロパティを変更するRuby

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 
+0

多分この問題はあなたのために大きすぎます。もっと小さなものを試しましたか? –

+0

他にどのように私はこれにアプローチできますか?これは私の割り当てです。私はプログラミングに関して何かを知っています。これは一般的に私の最初の選択ではないRubyを使う必要があります... – cAMPy

+0

もし私があなただったら、誰かに支払って私のためにコードを見てください。そして、コードについての私の質問に答えてください(私は後で私の割り当てを守ることができます)。 –

答えて

1

私はあなたがしようとしているのかわからないのですが、私は、小さな控えめなセットにあなたの問題を打破あなたを示唆して解決するだろう最後に、その後のセットは、一度に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のArrayクラスとHashクラスを調べて、どのようにデータ構造を操作できるかを確認することです。 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 

あなたはeachまたはeach_with_keyのような単純な方法で起動することができます。だから我々はこのような何かを行うことができます。それらと一緒に遊んでください。

これを理解すれば、これらのすべての概念をまとめたclassの構築を考え始めることができます。あなたは一歩を考えていない場合は、Stackoverflowで再度尋ねてみることができますが、非常に具体的であることを尋ねることができます(そして、言語にあまり親しまれていないが、英語)。

これが役に立ちます。幸運:)

関連する問題