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

Rubyで文字列配列を数値(整数)配列に変換する方法

More than 1 year has passed since last update.

for文を使う方法

strings = ["1", "2", "3", "4", "5"]

integers = []
for n in strings
  integers.push(n.to_i)
end
# integers => [1, 2, 3, 4, 5]

mapメソッドを使う方法

strings = ["1", "2", "3", "4", "5"]

integers = strings.map{|n| n.to_i}
# integers => [1, 2, 3, 4, 5]

または、

strings = ["1", "2", "3", "4", "5"]

integers = strings.map(&:to_i)
# integers => [1, 2, 3, 4, 5]

でもOKです。配列の各値が&となり、:メソッド名が適用されます。

なお、mapmap!(破壊的メソッド)にすると、レシーバー(strings)自体が整数の配列に上書きされます。

strings = ["1", "2", "3", "4", "5"]

strings.map!(&:to_i)
# strings => [1, 2, 3, 4, 5]
kota-es
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