ruby 将数组转换为哈希,其中键是索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14528560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:41:45  来源:igfitidea点击:

Convert an array to hash, where keys are the indices

ruby

提问by MxLDevs

I am transforming an array into a hash, where the keys are the indices and values are the elements at that index.

我正在将数组转换为散列,其中键是索引,值是该索引处的元素。

Here is how I have done it

这是我如何做到的

# initial stuff
arr = ["one", "two", "three", "four", "five"]
x = {}

# iterate and build hash as needed
arr.each_with_index {|v, i| x[i] = v}

# result
>>> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Is there a better (in any sense of the word "better") way to do it?

有没有更好的(在任何意义上的“更好”这个词)的方法来做到这一点?

回答by Kyle

arr = ["one", "two", "three", "four", "five"]

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

回答by tokland

Ruby < 2.1:

红宝石 < 2.1:

Hash[arr.map.with_index { |x, i| [i, x] }]
#=> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Ruby >= 2.1:

红宝石 >= 2.1:

arr.map.with_index { |x, i| [i, x] }.to_h

回答by sawa

x = Hash.new{|h, k| h[k] = arr[k]}

回答by Shairon Toledo

%w[one two three four five].map.with_index(1){ |*x| x.reverse }.to_h

Remove (1)if you want to start the index from 0.

(1)如果要从 开始索引,请删除0

回答by mober

Here is a solution making use of Object#tap, to add values to a newly-created hash:

这是一个使用Object#tap, 将值添加到新创建的哈希的解决方案:

arr = ["one", "two", "three", "four", "five"]

{}.tap do |hsh|
  arr.each_with_index { |item, idx| hsh[idx] = item }
end
#=> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

回答by Camille Drapier

Many good solutions already, just adding a variant (provided you do not have duplicated values):

已经有很多好的解决方案,只需添加一个变体(前提是您没有重复的值):

["one", "two", "three", "four", "five"].map.with_index.to_h.invert
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

回答by hurikhan77

You could monkey patch Arrayto provide a new method:

您可以使用猴子补丁Array来提供一种新方法:

class Array
  def to_assoc offset = 0
    # needs recent enough ruby version
    map.with_index(offset).to_h.invert
  end
end

Now you can do:

现在你可以这样做:

%w(one two three four).to_assoc(1)
# => {1=>"one", 2=>"two", 3=>"three", 4=>"four"}

This is a common operation I'm doing in Rails apps so I keep this monkey patch around in an initializer.

这是我在 Rails 应用程序中执行的常见操作,因此我将这个猴子补丁保留在初始化程序中。