简体   繁体   中英

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. Crucially, if the user just hits enter and doesn't provide a new value, the old value should survive. Here is my sample code, which works but does not seem particularly Ruby-idiomatic:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM