Reputation: 2094
I'm currently working on a project where I need to loop through an array of strings, convert those strings into arrays, and push those arrays into a larger array. Some of the strings have word duplication, so I need to remove that as well. I want to avoid hard-coding everything, so I'm trying to write as many functions as I can.
Here's an example of what I'm talking about.
old_array = ['Lilies are lovely lovely', 'Roses are romantic romantic', 'Daisies are bright bright']
new_array = []
Here's what the new array should look like:
new_array = [['Lilies', 'are', 'lovely'], ['Roses', 'are', 'romantic'], ['Daisies', 'are', 'bright']]
So the strings from old_array must be transformed into sub-arrays, with duplicate words removed.
I've been trying this and variations for a while, and it's not working very well.
def s_to_a(array)
array.each do |string|
string.split(" ").uniq
new_array.push(string) #pretty sure this is incorrect
end
end
s_to_a(old_array)
The error I keep getting is that new_array is an undefined local variable because I initialized it outside the function. Am I going about this the wrong way? Anyone have any pointers?
Upvotes: 1
Views: 1332
Reputation: 931
This sort of thing is easiest done with map
, like so:
new_array = old_array.map{|s| s.split.uniq }
map
is an Enumerable
method that converts or "maps" the enumerable object it is called on (often an array
) into a new array
. This is more convenient than manually pushing into sub-arrays with nil-checking.
The String
method split
by default splits on whitespace characters, so we can just call it without an argument and it will return an array of words. For a bit more detail... split
uses $;
as its default parameter, which is Ruby's global field separator variable... if the field separator is nil, which it is by default, split
defaults to whitespace separation.
Upvotes: 5