简体   繁体   English

Ruby哈希迭代,索引访问和值映射

[英]Ruby hash iteration, index access and value mapping

I have a hash with values paired to array-type values like so: 我有一个哈希,其值与数组类型值配对,如下所示:

someHash={:key1=>[element1a,element1b],:key2=>[element2a,element2b]}

I tried to iterate over the Hash, access indices and modifying the Hash's array-type values like so: 我试图遍历Hash,访问索引并修改Hash的数组类型值,如下所示:

hash.each_with_index{|(key,array),index|
    element1,element2 = array
    element1 = "new value"; element2="new value2"
}
hash

However, when I return the hash, the update has not occurred. 但是,当我返回哈希值时,没有发生更新。 Is there a hash method like the map! 有没有像map!这样的哈希方法map! method for arrays I can use (or a different workaround)? 我可以使用的数组方法(或其他解决方法)?

Your code just assigns values to some local variables. 您的代码只是将值分配给一些局部变量。 You need to assign the new values to the hash itself: 您需要将新值分配给哈希本身:

hash.each_with_index do |(key, array), index|
  element1, element2 = array
  element1 = "new value"
  element2 = "new value2"
  hash[key] = [element1, element2]
end

Or shorter (depending on what you try to achieve): 或更短(取决于您要实现的目标):

hash.each do |key, array|
  hash[key] = ["new value", "new value2"]
end

Or: 要么:

hash.update(hash) do |key, array|
  ["new value", "new value2"]
end

When you do this: 执行此操作时:

element1, element2 = array

You are creating pointers to the elements in the array. 您正在创建指向数组中元素的指针。 When you later do this: 当您稍后执行此操作时:

element1 = "new value"; element2="new value2"

You are settings those pointers to point to the new values, hence not modifying the initial array. 您正在设置这些指针以指向新值,因此不修改初始数组。

One solution is: 一种解决方案是:

hash.each_with_index do |(key,array),index|
    array[0] = "new_value"
    array[1] = "new value2"
end

hash

I would however do something like this instead: 但是,我将改为执行以下操作:

hash.each do |key, array|
    array[0] = "new_value"
    array[1] = "new value2"
end

hash

You don't need each_with_index. 您不需要each_with_index。 In fact, each_with_index doesn't exist for hash (the key is the index). 实际上,散列不存在each_with_index(键是索引)。 You can just do this: 您可以这样做:

some_hash.each do |key, value|
    value[0], value[1] = "new value", "new value2"
end

The problem in your code is that you are only changing the local references and not the values in the array. 代码中的问题在于,您仅更改本地引用,而不更改数组中的值。

You can use map like that: 您可以使用如下map

new_hash = Hash[hash.map{|k,v| [k, ["new value","new value2"]]}]

This won't change the original hash. 这不会更改原始哈希。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM