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 告诉我每个枚举元素都已处理,但结果并未保存在我的 hashwhat中。

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返回一个数组(在这种情况下是一个由两个元素键/值对组成的数组),并且Hash.[]可以[ [a,b], [c,d] ]变成{ a=>b, c=>d }.

你所做的——<code>hash.map{ … }——将每个键/值对映射到一个新值并创建一个数组……然后对该数组什么都不做。虽然存在破坏性 Array#map!地改变数组的方法,但没有等同Hash#map!于在一个步骤中破坏性地改变散列。


另请注意,如果您想破坏性地改变 Hash 或引用其他可变对象的任何其他对象,您可以在正常迭代期间破坏性地改变这些对象:

# 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 回答
1

代替:

w[1] = correction.chop!.to_sym

尝试直接分配给哈希:

what[w[0]] = correction.chop!.to_sym

Ruby is creating that w array just to pass you the key and value. Assigning to that array isn't going to change your hash; it's only changing that temporary array.

于 2013-03-30T03:40:15.950 回答