NothingToSeeHere
NothingToSeeHere

Reputation: 2373

Convert array of strings to an array of integers

I need to convert strings in an array representing numbers into integers.

["", "22", "14", "18"]

into

[22, 14, 18]

How can I do this?

Upvotes: 25

Views: 34863

Answers (2)

Stefan
Stefan

Reputation: 114268

You could select the strings containing digits using grep:

["", "22", "14", "18"].grep(/\d+/)
#=> ["22", "14", "18"]

And convert them via to_i by passing a block to grep:

["", "22", "14", "18"].grep(/\d+/, &:to_i)
#=> [22, 14, 18]

Depending on your input, you might need a more restrictive pattern like /\A\d+\z/.

Upvotes: 7

Ziv Galili
Ziv Galili

Reputation: 1445

To convert a string to number you have the to_i method.

To convert an array of strings you need to go through the array items and apply to_i on them. You can achieve that with map or map! methods:

> ["", "22", "14", "18"].map(&:to_i)
# Result: [0, 22, 14, 18]

Since don't want the 0 - just as @Sebastian Palma said in the comment, you will need to use an extra operation to remove the empty strings: (The following is his answer! Vote for his comment instead :D)

> ["", "22", "14", "18"].reject(&:empty?).map(&:to_i)
# Result: [22, 14, 18]

the difference between map and map! is that map will return a new array, while map! will change the original array.

Upvotes: 45

Related Questions