4

2 つの配列をハッシュに結合しようとしています。

@sample_array = ["one", "Two", "Three"]
@timesheet_id_array = ["96", "97", "98"]

結果を @hash_array というハッシュに出力したいと考えています。最後にプットを呼び出すと、コンソールで次のように見えるように、コードブロックで2つを組み合わせる簡単な方法はありますか

{"one" => "96", "Two" => "97", "Three" => "98"}

これは、1 行または 2 行のコードで実行できると思います。

4

5 に答える 5

40

これを試して

keys = [1, 2, 3]
values = ['a', 'b', 'c']
Hash[keys.zip(values)]

ありがとう

于 2012-10-02T17:30:06.140 に答える
8
@hash_array = {}
@sample_array.each_with_index do |value, index|
  @hash_array[value] = @timesheet_id_array[index]
end
于 2012-10-02T17:29:55.430 に答える
0
@hash_array = {}
0.upto(@sample_array.length - 1) do |index|
  @hash_array[@sample_array[index]] = @timesheet_id_array[index]
end
puts @hash_array.inspect
于 2012-10-02T17:27:32.230 に答える