Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@ononao0

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

More than 1 year has passed since last update.

前提

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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ononao0
秋なのでさんまが食べたいです。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?