Reputation: 17
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
Reputation: 110755
arr.first.split('')
#=> ["a", "b", "c", "d"]
arr.first
#=> "abcd"
Upvotes: 2
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
Reputation: 3984
Q1:
arr.map(&:chars).flatten
#=> ["a", "b", "c", "d"]
Q2:
arr = arr[0]
#=> "abcd"
Upvotes: 0
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