0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby] 配列の中の文字列を数値に一括変換する方法

Last updated at Posted at 2021-01-01

はじめに

配列の中の数値を変換しようとしたときにつまずき書き方を調べたので
備忘録として自分用にメモしていきます。

問題

配列の中の文字列の数を変換しようとした際に、
エラーが出てしまいました。

array.rb
Traceback (most recent call last):
array.rb:3:in `<main>': undefined method `to_i' for ["1", "2", "3", "4", "5"]:Array (NoMethodError)
Did you mean?  to_s
               to_a
               to_h

書き方の例についてのまとめです。↓↓↓

whileメソッド

array.rb
num = [ "1", "2", "3", "4", "5" ]

i = 0
while i <= 4
  num[i] = num[i].to_i
  i += 1
end

p num
# =>[1, 2, 3, 4, 5]

for文

array.rb
num = [ "1", "2", "3", "4", "5" ]

int = []
for i in num
  int.push(i.to_i)
end

p int
# =>[1, 2, 3, 4, 5]

mapメソッド

array.rb
num = [ "1", "2", "3", "4", "5" ]

int = num.map{ |i| i.to_i }

p int
# =>[1, 2, 3, 4, 5]
array.rb
num = [ "1", "2", "3", "4", "5" ]
int = num.map(&:to_i)

p int
# =>[1, 2, 3, 4, 5]

まとめ

なかなかうまく変換できなかったのでこれを機会に調べてみました。
これでもう少しわかりやすく記述できそうです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?