LoginSignup
1
1

More than 1 year has passed since last update.

【Ruby on Rails】複数の配列を結合しハッシュのネストに追加する方法

Last updated at Posted at 2023-02-11

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4

やりたいこと

下記データを結合し、ハッシュのネストに追加したい。

@fruits = [['りんご','赤','丸い'],['メロン','緑','丸い'],['バナナ','黄','細長い'],...]
@vegetables = [['大根','白','細長い'],['トマト','赤','丸い'],['キャベツ','緑','丸い'],...]

方法

1. ハッシュのネストを作成する

実装
# ハッシュのネストを作成する
hash = Hash.new {|h1, k1|
  h1[k1] = Hash.new {|h2, k2|
    h2[k2] = []
  }
}

2. ハッシュのネストにデータを投入する

実装
@fruits.each do |fruit|
  # 変数を定義する
  fruit_color = fruit[1]
  fruit_shape = fruit[2]
  
  @vegetables.each do |vege|
    # 変数を定義する
    vege_color = vege[1]
    vege_shape = vege[2]

    # fruitデータとvegeデータをcolorとshapeで結合する
    if fruit_color === vege_color && fruit_shape === vege_shape
      # ハッシュにcolorとshapeを追加する
      hash = hash[fruit_color][fruit_shape]
      # ハッシュにfruitデータを追加する
      hash.push(fruit)
      # ハッシュにvegeデータを追加する
      hash.push(vege)
    end
  end
end
結果
{"赤"=>
 {"丸い"=>
  [['りんご','赤','丸い'], ['トマト','赤','丸い'], ...]},
 "緑"=>
  {"丸い"=>
   [['メロン','緑','丸い'], ['キャベツ','緑','丸い'], ...]},
  {"細長い"=>
   [['きゅうり','緑','細長い'], ['ゴーヤ','緑','細長い'], ...]},
...
}

参考

1
1
0

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
1
1