26

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

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

into

[22, 14, 18]

How can I do this?

7
  • 9
    With empty values it would require an extra operation, maybe like ["", "22", "14", "18"].reject(&:empty?).map(&:to_i). Commented Jan 23, 2018 at 23:06
  • 1
    @SebastianPalma why dont you answer? Commented Jan 23, 2018 at 23:10
  • @SebastianPalma I'm not sure he needs any special operation, as rails will convert empty string to 0 when you use to_i so ["", "22", "14", "18"].map(&:to_i) should be enough! (The result will be: [0, 22, 14, 18], so if you don't want a 0 in the result, you do need the extra operation) Commented Jan 23, 2018 at 23:24
  • I think maybe Integer#to_i is implemented in Ruby as in Rails, in both cases it returns 0, but the output added doesn't contain a 0 as first value, that's why, it lacks info. Commented Jan 23, 2018 at 23:27
  • Core implements String#to_i Commented Jan 23, 2018 at 23:31

2 Answers 2

46

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If using Rails compact_blank will make it work if the array contains a mix of integers and strings e.g. ["", "22", "14", "18" ,123].compact_blank.map(&:to_i)
7

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/.

2 Comments

This is super nice but it is worth noting that if the array already contains integers it will reject them.
@rmaspero true, but the OP specifically asked to "Convert array of strings to an array of integers", hence the use of grep and a regular expression. Handing mixed arrays is something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.