1

I have below string

ids = ["4,5,6"]

when I do

ids = ["4,5,6"].split(',')

Then I get ids as [["4,5,6"]]

can I do something to get ids as [4, 5, 6] ?

1
  • 1
    Where does ids come from in the first place? I would understand ids = ["4" ,"5", "6"] or ids = "4,5,6" but that string within an array smells like a bug elsewhere. Commented Jul 6, 2020 at 11:58

3 Answers 3

1

You're trying to split an array, try to split a string instead:

["4,5,6"].first.split(',')
#=> ["4", "5", "6"]

After that you can simply convert it to an array of ints:

["4", "5", "6"].map(&:to_i)
#=> [4, 5, 6]
Sign up to request clarification or add additional context in comments.

Comments

1

There are many ways to do it. More generic version (if you expect more than one string in the original array e.g.: ["4,5,6", "1,2,3"]):

> ["4,5,6"].flat_map{ |i| i.split(',') }.map(&:to_i)
=> [4, 5, 6]
> ["4,5,6", "1,2,3"].flat_map{ |i| i.split(',') }.map(&:to_i)
=> [4, 5, 6, 1, 2, 3]

2 Comments

Because ["4,5,6", "1,2,3"].map{ |i| i.split(',') } => [["4", "5", "6"], ["1", "2", "3"]]
one could do ["4,5,6", "1,2,3"].map{ |i| i.split(',') }.flatten(1) but it's discouraged (for example) by RuboCop, not sure why exactly...
1

My answer appears to be less concise than the accepted one and I'm fairly new to Ruby. I think that you can use ! to alter the Array in place.

Problem: Original Array with 1 element as a String

ids=["4,5,6"];

Goal: Array with 3 elements of Integers

new_ids=[];

Process:

  1. Convert the Array to a String
  2. Create a new Array where each element is created by the comma ','
  3. Convert each element to an Integer
  4. Push each Integer Element to the Goal Array
new_ids.flatten.each do |i| new_ids.push(i.to_i) end;

Results: Display the New Integer Array

new_ids
[4, 5, 6]

2 Comments

Good job, spelling out the steps. I recommend to get familiar with map and passing a method into an enumerator. There are often more direct approaches than with .each, and you will see a lot of ruby code, you will not understand, if you do not now .map .inject .reduct and stuff like .map(&:to_i)
Thank you @RolandStuder :-D

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.