36

配列をハッシュに変換しています。キーはインデックスで、値はそのインデックスの要素です。

これが私がやった方法です

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

それを行うためのより良い(「より良い」という言葉の意味で)方法はありますか?

4

7 に答える 7

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

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}
于 2013-01-25T19:00:49.957 に答える
27

ルビー < 2.1:

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

ルビー >= 2.1:

arr.map.with_index { |x, i| [i, x] }.to_h
于 2013-01-25T19:14:09.590 に答える
4
x = Hash.new{|h, k| h[k] = arr[k]}
于 2013-01-25T19:46:27.433 に答える
2

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"}
于 2018-06-25T11:33:56.113 に答える