0

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

1
  • Your code will not give arr=["a","b","c","d"]. Do you want to replace arr in place or not? Commented Mar 12, 2016 at 20:16

5 Answers 5

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

arr.first
  #=> "abcd"
Sign up to request clarification or add additional context in comments.

1 Comment

This is great. I'd never have thought of this. Thank you Cary!
0

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"

Comments

0

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.

Comments

0

Q1:

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

Q2:

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

1 Comment

Prefer flat_map(&:chars) to map(&:chars).flatten.
0

This is one way:

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

Comments

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.