I want to convert a given sentence into an array of arrays, where each nested array consists of the letters of each word, so that "I am a dog" becomes [["I"], ["a", "m"], ["a"], ["d", "o", "g"]], for instance.
I can split the sentence into individual words using .split(" "), and I can divide the individual words into letters using .chars, but I can't manage to combine the two. When I split first and then iterate:
sentence.split(" ")
sentence.each { |word| word.chars }
... it just returns the array of words without doing the second part. I've tried several different variations (using .each_with_index, or by saying "word = word.chars" and so on) of this code but just can't get it to do what I want. What's the best way to do this?
CodePudding user response:
You should use Enumerable#map.
sentence.split(" ").map { |word| word.chars }