How to change hash keys
我有一个这样的哈希:
1 2 | test => {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} |
我想获取哈希中的每个键并删除数字后面的所有字符,例如:
"qtc-1测试"应等于"qtc-1"
我已经接近解决方案,但还没有完全解决:
1 2 3 4 5 | str = test.keys[0] =>"QTC-1 test" new = str.slice(0..(str.index(/\d/))) =>"QTC-1" |
但是需要一些帮助来使用哈希键。
奖金
将值更改为相应的数值:
因此,如果value=pass,则将其更改为1;如果value=fail,则将其更改为2。
可能的奖励答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | scenarios.each_pair { |k, v| case v when 'pass' scenarios[k] = 1 when 'fail' scenarios[k] = 2 when 'block' scenarios[k] = 3 else scenarios[k] = 4 end } |
使用Ruby 2.1.2:
1 2 3 | test = {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} (test.keys.map { |k| k.sub /\stest\z/, '' }.zip test.values).to_h #=> {"QTC-1"=>"pass","QTC-2"=>"fail"} |
这里的想法是从每个键中去掉字符串"test",将其与原始哈希中的值压缩在一起,然后将得到的数组转换回哈希。
此答案修改原始哈希,而不是创建新哈希。
1 2 3 | h = {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} h.keys.each{|k| h[k[/.*\d+/]] = h.delete(k)} h #=> {"QTC-1"=>"pass","QTC-2"=>"fail"} |
1 | h = {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} |
使用哈希转换键。只换钥匙
1 | h.transform_keys {|k| k.sub /\stest\z/, '' } |
奖金部分:
要从"pass"或"fail"更新到新修改的哈希的数值,可以将
1 2 3 | test = {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} test.each_pair { |k, v| v =="pass" ? test[k] = 1 : test[k] = 2 } # => {"QTC-1 test"=>1,"QTC-2 test"=>2} |
更新有比"通过"和"失败"更多选项的情况…您可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | test = { "QTC-1 test" =>"pass", "QTC-2 test" =>"fail", "QTC-3 test" =>"blocked", "QTC-4 test" =>"denied", "QTC-5 test" =>"other", "QTC-6 test" =>"error" } test.each_pair do |k, v| case v when"pass" test[k] = 1 when"fail" test[k] = 2 when"blocked" test[k] = 3 when"denied" test[k] = 4 when"other" test[k] = 5 else test[k] ="well dangit, I don't know what to do with #{v}" end end p test => {"QTC-1 test"=>1, "QTC-2 test"=>2, "QTC-3 test"=>3, "QTC-4 test"=>4, "QTC-5 test"=>5, "QTC-6 test"=>"well dangit, I don't know what to do with error"} |
1 2 3 | h = {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} Hash[h.map { |k,v| [k.sub(/(?<=\d).*/, ''), v] }] # => {"QTC-1"=>"pass","QTC-2"=>"fail"} |
1 2 3 4 5 | new_hash = {} old_hash = {"QTC-1 test"=>"pass","QTC-2 test"=>"fail"} old_hash.map{|key, value| new_hash[key.split("").first]=value} p new_hash |