LoginSignup
15
13

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-11-17

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]
15
13
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
15
13