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?
old_array = ['a b b', 'b a b']? Ifold_array = ['pound a pound of nails]?new_array = []as the first line inside your method, then your code works. But as @Cam says you should useEnumerable#mapin this case.