LoginSignup
0
0

More than 3 years have passed since last update.

備忘録:Railsにおける多次元配列のリファクタリングについて(+ jsonでの受渡しについて)

Last updated at Posted at 2019-10-21

前提

json形式で配列を送りたかったが、配列が別々に2つ存在するため多次元配列(2次元配列)を作る必要があった。

最初

name.rb
names = ["hideki", "takahiro", "miki"]
descriptions = ["すごい", "かっこいい", "かわいい"]

inventories = []

names.each_with_index do |name, i|
  inventories.push [name, descriptions[i]]
end

出力結果

 [["hideki", "すごい"], ["takahiro", "かっこいい"], ["miki", "かわいい"]]

改善

name.rb
names = ["hideki", "takahiro", "miki"]
descriptions = ["すごい", "かっこいい", "かわいい"]

inventories = names.zip(descriptions)

出力結果

 [["hideki", "すごい"], ["takahiro", "かっこいい"], ["miki", "かわいい"]]

メモ:受け取り側での処理

上記をjson形式で送る

name.rb
render json: inventories

ループさせる

name.coffee
success: (json) ->
  html = ""
  for i of json
    html += "<div class='name'>#{json[i][0]}</div><div class='description'>#{json[i][1]}</div>"
  $(".names").html(html)

上記の[0][1]をループさせる方法がわからずでして、、どなたかわかる方がいらっしゃいましたら教えて頂けるとうれしみです。。

参考にした記事

Rubyの配列でごにょごにょするときzipとinjectとevalが便利すぎる件

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