简体   繁体   English

什么是最惯用的 Ruby 方式来逐步通过 hash,在每一步更新值?

[英]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.

相关问题 在Ruby中更新哈希键的惯用方式是什么? - What is an idiomatic way to update hash keys in Ruby? 在ruby中执行多项测试的最惯用方法是什么? - What is the most idiomatic way to perform multiple tests in ruby? 使用Ruby,最有效的方法是检查哈希中的任何键是否匹配数组中的任何值 - Using Ruby, what is the most efficient way to check if any key in a hash matches any values within an Array 在ruby siteprism中重用步骤定义的最佳方法是什么 - What's the best way to reuse your step definition in ruby siteprism Ruby:修改哈希数组的最惯用方式? - Ruby: Most idiomatic way to modify an array of hashes? Ruby:使用`.each`或`.step`,为每次迭代前移随机量 - Ruby: using `.each` or `.step`, step forward a random amount for each iteration 迭代Ruby数组的最惯用的方法,当满足任意条件时退出? - The most idiomatic way to iterate through a Ruby array, exiting when an arbitrary condition met? Ruby + Selenium-执行每个步骤后截屏 - Ruby + Selenium - Take a screenshot with each step executed 在OS X上的运行时逐步浏览Ruby代码 - Step through Ruby code at runtime on OS X 在Ruby中构造AST的惯用方式是什么? - What is the idiomatic way to construct an AST in Ruby?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM