arjweb
arjweb

Reputation: 43

String into a multi-dimensional array in Ruby?

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

Answers (2)

Uri Agassi
Uri Agassi

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

Arup Rakshit
Arup Rakshit

Reputation: 118261

How about below :

my_string = "Made up of several words"
my_string.scan(/(\w+)/) 
# => [["Made"], ["up"], ["of"], ["several"], ["words"]]

Upvotes: 5

Related Questions