小编use*_*083的帖子

从Ruby中的哈希数组中删除哈希

我有一系列哈希如下:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]
Run Code Online (Sandbox Code Playgroud)

现在,我想首先检查数组是否包含"k1"带有值的键的哈希"v3".如果是,那么我想从数组中删除该哈希.

结果应该是:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]
Run Code Online (Sandbox Code Playgroud)

ruby arrays hash

13
推荐指数
2
解决办法
1万
查看次数

Ruby中的数组哈希

我有一个哈希,其中key是一个字符串,value是一个字符串数组.我想要这样的东西:

{"k1"=>["v1", "v2"], "k2"=>["v3", "v4"]} 
Run Code Online (Sandbox Code Playgroud)

我只有一个哈希和一个数组来实现这一点.我编写了这样的代码:

hash1 = Hash.new
arr = Array.new
arr.push "v1"
arr.push "v2"
hash1["k1"] = arr 

#hash is like this: {"k1"=>["v1", "v2"]
#Now I clear the array to read the new values

arr. clear
arr.push "v3"
arr.push "v4"
hash1["k2"] = arr
puts hash1

#Output: {"k1"=>["v3", "v4"], "k2"=>["v3", "v4"]}
#Notice that k1's value also got updated
Run Code Online (Sandbox Code Playgroud)

然后我换了一行:

hash1 = Hash.new
arr = Array.new
arr.push "v1"
arr.push "v2"
hash1["k1"] = arr 

arr = [] # ** This is the …
Run Code Online (Sandbox Code Playgroud)

ruby arrays hash

10
推荐指数
1
解决办法
2万
查看次数

标签 统计

arrays ×2

hash ×2

ruby ×2