5

In my app, I have a textfield in which the user enters something like this

"1,2,3,4"

which gets stored to the database. Now, when I want to use the inner numbers, i have two options:

"1,2,3,4".split(',')

OR

string.scan(/\d+/) do |x|
    a << x
end

Both ways i get an array like

 ["1","2","3","4"] 

and then i can use the numbers by calling to_i on each one of them.
Is there a better way of doing this, that converts

"1,2,3" to [1,2,3] and not ["1","2","3"]

4 Answers 4

13
str.split(",").map {|i| i.to_i}

but the idea is same to you....

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

2 Comments

And in 1.8.7p302: str.split(',').map(&:to_i)
I thought &:to_i was kinda frowned upon due to performance issues. No? Good for people to know that it exists though for sure.
1

You can do this.

t = "1,2,3,4".split(',').collect{|n| n.to_i}

Comments

0

In Ruby 1.9.3 you can do the following:

No space after the comma:

"1,2,3,4".split(',')  # => ["1","2","3","4"]

With the space after the comma:

"1,2,3,4".split(', ')  # => ["1,2,3,4"]

No space after the comma:

"1,2,3,4".split(',').map(&:to_i)  # => [1,2,3,4]

With a space after the comma, you are going to get this:

"1,2,3,4".split(', ').map(&:to_i)  # => [1]

Comments

-3

You can do it by following method:- "1,2,3,4".split(/,/)

This will give you following result:-

["1", "2", "3", "4"]

Thanks....

1 Comment

Question is how to get [1,2,3,4] :p

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.