Reputation: 397
I have an array (which is technically a string) of id numbers.
ids = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
I want to make the ids into an array that looks like this:
ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The only way I've found to do this is to use map.
id_numbers = ids.split(/,\s?/).map(&:to_i)
However, this lops off the first number in the array and replaces it with 0.
id_numbers = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Is there a better way to go about converting a string array into a regular array?
Upvotes: 1
Views: 885
Reputation: 401
To summarize: you get 0
as first element in the array because of non-digital character at the beginning of your string:
p '[1'.to_i #=> 0
Maybe there is a better way to recieve original string. If there is no other way to recieve that string you can simply get rid off first character and your own solution will work:
ids = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11]"
p ids[1..-1].split(",").map(&:to_i)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11]
@tadman's and @CarySwoveland's solutions work perfectly fine. Alternatively:
ids = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11]"
p ids.tr("^-0-9", ' ').split.map(&:to_i)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11]
Keep in mind that &:
first appeared in Ruby 1.8.7.
Upvotes: 0
Reputation: 110755
If you do not wish to use JSON
,
ids.scan(/\d+/).map(&:to_i)
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If ids
may contain the string representation of negative integers, change the regex to /-?\d+/
.
Upvotes: 3
Reputation: 211750
Since this is actually in JSON format the answer is easy:
require 'json'
id_json = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
ids = JSON.load(id_json)
The reason your solution "lops off" the first number is because of the way you're splitting. The first "number" in your series is actually "[1"
which to Ruby is not a number, so it converts to 0 by default.
Upvotes: 5