[英]What is the most idiomatic Ruby way to step through a hash, updating values at each step?
I want to step through a simple hash, showing the value for each key-value pair, and give the user the ability to update that value.我想逐步完成一个简单的 hash,显示每个键值对的值,并让用户能够更新该值。 Crucially, if the user just hits enter and doesn't provide a new value, the old value should survive.至关重要的是,如果用户只是按 Enter 键并且没有提供新值,那么旧值应该会继续存在。 Here is my sample code, which works but does not seem particularly Ruby-idiomatic:这是我的示例代码,它有效,但似乎不是特别符合 Ruby 语言习惯:
mydata = {"key1" => "value1", "key2" => "value2", "key3" => "value3"}
newdata = {}
mydata.each do |k, v|
puts "current value is " + v.to_s
input = gets.chomp
if input.length == 0
newdata[k] = mydata[k]
else
newdata[k] = input
end
end
puts mydata
puts newdata
If you really don't care about the keys:如果你真的不关心钥匙:
newdata = mydata.transform_values do |value|
puts "Current: #{value.inspect}"
updated = gets.chomp
updated.empty? ? value : updated
end
That's all there is to it.这里的所有都是它的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.