I need to convert strings in an array representing numbers into integers.
["", "22", "14", "18"]
into
[22, 14, 18]
How can I do this?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With