Reputation: 43
Really newb question, sorry. I have a string like this made up of several words and want to turn it into an array where each word is a sub array within an array.
my_string = "Made up of several words"
my_array = []
my_string.split(/\s/) do |word|
my_array << word
end
gives me
["Made", "up", "of", "several", "words"]
but I want to get:
[["Made"], ["up"], ["of"], ["several"], ["words"]]
Anyone know how I can do this please? I'm using the do end syntax because I want a code block where next I can add some logic around what I do with certain words coming in from the string. Thanks.
Upvotes: 2
Views: 232
Reputation: 37409
Would this work?
my_string = "Made up of several words"
my_array = my_string.split(/\s+/).map do |word|
[word]
end
# => [["Made"], ["up"], ["of"], ["several"], ["words"]]
Upvotes: 3
Reputation: 118261
How about below :
my_string = "Made up of several words"
my_string.scan(/(\w+)/)
# => [["Made"], ["up"], ["of"], ["several"], ["words"]]
Upvotes: 5