2

これが私のサンプルプログラムです:

what = {:banana=>:fruit, :pear=>:fruit, :sandal=>:fruit, :panda=>:fruit, :apple=>:fruit}

what.map do |w| 
    p "is this right?"
    awesome_print w
    fix = gets
    fix.chop!
    if (fix == "N")
        p "Tell me what it should be"
        correction = gets
        w[1] = correction.chop!.to_sym
    end
    p w
end

私はそれを実行し、これを取得します(私の入力が含まれています):

"is this right?"
[
    [0] :banana,
    [1] :fruit
]
Y
[:banana, :fruit]
"is this right?"
[
    [0] :pear,
    [1] :fruit
]
Y
[:pear, :fruit]
"is this right?"
[
    [0] :sandal,
    [1] :fruit
]
N
"Tell me what it should be"
footwear
[:sandal, :footwear]
"is this right?"
[
    [0] :panda,
    [1] :fruit
]
N
"Tell me what it should be"
animal
[:panda, :animal]
"is this right?"
[
    [0] :apple,
    [1] :fruit
]
Y
[:apple, :fruit]
=> [[:banana, :fruit], [:pear, :fruit], [:sandal, :footwear], [:panda, :animal], [:apple, :fruit]]
>> what
=> {:banana=>:fruit, :pear=>:fruit, :sandal=>:fruit, :panda=>:fruit, :apple=>:fruit}

私の質問は、ハッシュを変更するにはどうすればよいですか? irb は、プログラムを実行すると、列挙された各要素が処理されることを通知しますが、結果は hash に保存されませんwhat

4

2 に答える 2

5

ハッシュをその場で変更したい場合(あなたが望むように)、単にこれを行います:

my_hash.each do |key,value|       # map would work just as well, but not needed
  my_hash[key] = some_new_value    
end

元のハッシュを変更せずに新しいハッシュを作成する場合:

new_hash = Hash[ my_hash.map do |key,value|
  [ key, new_value ]
end ]

これが機能する方法Enumerable#mapは、配列 (この場合は 2 つの要素のキーと値のペアの配列)をHash.[]返し、 .[ [a,b], [c,d] ]{ a=>b, c=>d }

あなたがしていたのは — <code>hash.map{ … } — それぞれのキーと値のペアを新しい値にマッピングし、配列を作成することでした…そして、その配列に対して何もしませんでした。配列をその場で破壊的に変更するものはありますが、単一のステップでハッシュを破壊的に変更するのに相当するものはありませArray#map!Hash#map!


また、ハッシュ (または他の変更可能なオブジェクトを参照する他のオブジェクト) を破壊的に変更したい場合は、通常の反復中にそれらのオブジェクトを破壊的に変更するだけでよいことに注意してください。

# A simple hash with mutable strings as values (not symbols)
h = { a:"zeroth", b:"first", c:"second", d:"third" }

# Mutate each string value
h.each.with_index{ |(char,str),index| str[0..-3] = index.to_s }

p h #=> {:a=>"0th", :b=>"1st", :c=>"2nd", :d=>"3rd"}

ただし、サンプル コードでは値にシンボルを使用しており、シンボルは可変ではないため、この最後の注意事項はそこには直接適用されません。

于 2013-03-30T03:38:58.307 に答える