如何更改哈希键

时间:2014-08-19 15:16:38

标签: ruby hash

我有这样的哈希:

test
 => {"QTC-1 test"=>"pass", "QTC-2 test"=>"fail"}

我想在散列中取出每个键并删除数字后面的所有字符,例如:

“QTC-1测试”应该等于“QTC-1”

我接近解决方案但不完全在那里:

str = test.keys[0]
 => "QTC-1 test" 

new = str.slice(0..(str.index(/\d/)))
 => "QTC-1" 

但需要一些帮助,使用哈希键。

加成

将值更改为相应的数值:

因此,如果value = pass,则将其更改为1,如果value = fail,则将其更改为2.

奖金可能答案:

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

  }

6 个答案:

答案 0 :(得分:3)

使用Ruby 2.1.2:

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"}

这里的想法是你去除字符串"测试"从每个键中,将其与原始哈希值一起压缩,然后将生成的数组转换回哈希值。

答案 1 :(得分:2)

此答案修改原始哈希,而不是创建新哈希。

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"}

答案 2 :(得分:2)

h = {"QTC-1 test"=>"pass", "QTC-2 test"=>"fail"}

使用hash#transform_keys。它只会对键进行更改

h.transform_keys {|k| k.sub /\stest\z/, '' }

答案 3 :(得分:1)

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

答案 4 :(得分:1)

h = {"QTC-1 test"=>"pass", "QTC-2 test"=>"fail"}
Hash[h.map { |k,v| [k.sub(/(?<=\d).*/, ''), v] }]
# => {"QTC-1"=>"pass", "QTC-2"=>"fail"}

答案 5 :(得分:1)

奖金部分:

要将“通过”或“失败”更新为新修订的哈希值,您可以使用#each_pair条件。这里使用ternary operator格式:

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}

更新情况,其中有多个选项而不是“通过”和“失败”...您可以使用case声明:

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"}