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.
["", "22", "14", "18" ,123].compact_blank.map(&:to_i)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/.
grep and a regular expression. Handing mixed arrays is something else.
["", "22", "14", "18"].reject(&:empty?).map(&:to_i).0when you useto_iso["", "22", "14", "18"].map(&:to_i)should be enough! (The result will be:[0, 22, 14, 18], so if you don't want a0in the result, you do need the extra operation)String#to_i