Suman Das
Suman Das

Reputation: 301

How to convert a string of ids inside an array to array of ids without string in ruby?

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] ?

Upvotes: 1

Views: 773

Answers (3)

TheWind
TheWind

Reputation: 13

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]

Upvotes: 1

Ilya
Ilya

Reputation: 13477

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]

Upvotes: 1

Greg
Greg

Reputation: 6628

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]

Upvotes: 1

Related Questions