Help us understand the problem. What is going on with this article?

JSON型のデータを普通の配列のデータに変えたいとき

More than 1 year has passed since last update.

"[\"1\", \"2\"]"みたいなデータを[1, 2]みたいな普通の配列のデータにしたいときに自分用のメモとして書きたいと思います。

json = "[\"1\", \"2\"]"
array = JSON.parse(json)  #=> ["1", "2"]

すると、array

array #=> ["1", "2"]

みたいなデータになります。これをmapを使えば、[1, 2]というデータに変換できます。

array.map{|id| id.to_i} #=> [1, 2]

これをまとめて1行で書くと下記みたいになりますね。

JSON.parse(json).map{|id| id.to_i} #=> [1, 2]

追記

下記のコメントで初めて知ったのですが、mapのところでもっと簡単にかけます。

JSON.parse(json).map(&:to_i) #=> [1, 2]

ちなみに、ブロックの代わりに &:メソッド名 という引数を渡せる条件は、

・ブロック引数が1個である
・ブロックの中で呼び出すメソッドには引数がない
・ブロックの中では、ブロック引数に対してメソッドを1回呼び出す以外の処理がない

です。

Why do not you register as a user and use Qiita more conveniently?
  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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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