Dav*_*est 2 ruby hash block map
这是我的示例程序:
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
Run Code Online (Sandbox Code Playgroud)
我运行它,我得到了这个(我的输入包括在内):
"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}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何更改哈希?irb告诉我,当我运行程序时,每个枚举元素都被处理,但结果不会保存在我的哈希中what.
如果你想要改变哈希(就像你想要的那样),只需这样做:
my_hash.each do |key,value| # map would work just as well, but not needed
my_hash[key] = some_new_value
end
Run Code Online (Sandbox Code Playgroud)
如果要创建新哈希,而不更改原始哈希:
new_hash = Hash[ my_hash.map do |key,value|
[ key, new_value ]
end ]
Run Code Online (Sandbox Code Playgroud)
这种方式的工作方式是Enumerable#map返回一个数组(在这种情况下是一个双元素键/值对的数组),并且Hash.[]可以[ [a,b], [c,d] ]变成{ a=>b, c=>d }.
你在做什么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"}
Run Code Online (Sandbox Code Playgroud)
但是,由于您在示例代码中使用符号作为值,并且由于符号不可变,因此最终注释不会直接应用于此处.