2

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.

2 Answers 2

5

How about below :

my_string = "Made up of several words"
my_string.scan(/(\w+)/) 
# => [["Made"], ["up"], ["of"], ["several"], ["words"]]
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

That was the trick. Putting [ ] around the variable made it come through as an ARRAY as I needed. Thanks
If my_string were "Made up of several words" you would get => [["Made"], ["up"], [""], [""], [""], ["of"], ["several"], ["words"]]. Rather than split(/\s/),I think it would be better to just use split without an argument, which is the same as split(' '), which disregards extra whitespace.

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.