Iggy Iggy - 4 months ago 72
Ruby Question

ruby split string into array then split array elements into words

I want to perform deeper array method on a given string. Let's say I have

str = "hello world"


I can split it using
str.split(" ")
. But my intended goal is to turn
"hello"
into
["h", "e", "l", "l", "o"]
and
"world"
into
["w", "o", "r", "l", "d"]
so I can do array method of my choosing (like swapping first and last letter
["o", "e", "l", "l", "h"]
, and then returning it back into
["oellh", "dorlw"]
, and finally putting them back together
"oellh dorlw"
.

That's just an example method. There are several different array method I wish to apply, but it only works if the string is split into array of words, and further split into array of elements (
str.chars
is not what I am looking for). I tried
str.split(" ").each {|arr| arr.split("")}
but it does not work. What is the best method to split a string into an array, and splitting that array of words into array of elements, apply a method, and join them back into a string?

Answer
"hello world".split.map { |word| word[-1] + word[1..-2] + word[0] }.join(' ')
=> "oellh dorlw"
Comments