bscottyoung
bscottyoung

Reputation: 17

Ruby. How to split a string element inside an array?

I have an array of arr=["abcd"]

Q1. Is there a simpler way to split the 'abcd' into arr=["a","b","c","d"] than the following:

    arr=["abcd"]
    arr_mod=[]
    x=0
    while x < arr[0].size
        arr_mod << arr[0][x]
        x +=1
    end
    puts "==>#{arr_mod}"

arr.split('') will not work.

Q2. Is there a method to convert arr=["abcd"] to the string of "abcd"?

Upvotes: 0

Views: 4476

Answers (5)

Sagar Pandya
Sagar Pandya

Reputation: 9508

This is one way:

arr.join.split('') #=> ["a", "b", "c", "d"]

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110755

arr.first.split('')
  #=> ["a", "b", "c", "d"] 

arr.first
  #=> "abcd"

Upvotes: 2

TCannadySF
TCannadySF

Reputation: 286

Q1:

This would give you some flexibility in case you ever needed a way to iterate over an array of more than one element:

arr = ['abcd']
arr = arr[0].split("")
  #=> ["a", "b", "c", "d"]

Q2:

arr = ['abcd']
arr = arr[0]
  #=> "abcd"

Upvotes: 0

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

Q1:

arr.map(&:chars).flatten
#=> ["a", "b", "c", "d"]

Q2:

arr = arr[0]
#=> "abcd"

Upvotes: 0

TheSuper
TheSuper

Reputation: 645

Simplest way is to do

arr.join("").chars

This turns the arr into one big string, then turns that string into an array of characters.

For your second question, just do arr.join(""), which will turn all the strings into the array into one big string.

For more information, check out Array#join and String#chars for more detail.

Upvotes: 0

Related Questions