How to change hash keys

I have a hash like this:

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

I want to take each key in the hash and remove all characters after the numbers, example:

"QTC-1 test" should equal "QTC-1"

I am close to the solution but not fully there:

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

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

But need some help doing that with the hash key(s).

Bonus

Changing the values to corresponding number values:

So if value = pass then change it to 1 or if value = fail then change it to 2.

Bonus possible answer:

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

  }

这个答案修改了原始的哈希,而不是创建一个新的哈希。

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

With Ruby 2.1.2:

test = {"QTC-1 test"=>"pass", "QTC-2 test"=>"fail"}
(test.keys.map { |k| k.sub /stestz/, '' }.zip test.values).to_h 
#=> {"QTC-1"=>"pass", "QTC-2"=>"fail"}

The idea here is that you strip the string " test" from each key, zip it together with the values from your original hash, and then turn the resulting array back into a hash.


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
链接地址: http://www.djcxy.com/p/25648.html

上一篇: Ruby替代goto

下一篇: 如何更改散列键