Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of strings to an array of integers

Tags:

ruby

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

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

into

[22, 14, 18]

How can I do this?

like image 761
NothingToSeeHere Avatar asked Jan 23 '18 23:01

NothingToSeeHere


1 Answers

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.

like image 60
Ziv Galili Avatar answered Oct 25 '22 21:10

Ziv Galili