LoginSignup
2
0

More than 3 years have passed since last update.

【Ruby】要素数が等しい複数のarrayリストの、1つ目の要素から順にhashリストに保存する

Last updated at Posted at 2019-08-13

要素数が等しい3つのarrayリストがある。

array1 = [1,2,3,4,5]
array2 = [6,7,8,9,10]
array3 = [11,12,13,14,15]

各arrayリストについて、1つ目の要素から順にhashに保存して別メソッドの引数とする処理を書きたい。

p hash
#=>
{:first=>1, :second=>6, :third=>11}

zip関数を利用する

array.zip(other_array, ...)
https://ref.xaio.jp/ruby/classes/array/zip

array1 = [1,2,3,4,5]
array2 = [6,7,8,9,10]
array3 = [11,12,13,14,15]
hash = {}

array1.zip(array2, array3) do |a,b,c|
  hash[:first] = a
  hash[:second] = b
  hash[:third] = c
  p hash
end
#arrayの要素数分のhashが作成される。
#=>
{:first=>1, :second=>6, :third=>11}
{:first=>2, :second=>7, :third=>12}
{:first=>3, :second=>8, :third=>13}
{:first=>4, :second=>9, :third=>14}
{:first=>5, :second=>10, :third=>15}

文章で説明するのが非常に難しい

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0