1

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?

3
  • 1
    What is the desired result if old_array = ['a b b', 'b a b']? If old_array = ['pound a pound of nails]? Commented Jul 4, 2016 at 4:47
  • Put new_array = [] as the first line inside your method, then your code works. But as @Cam says you should use Enumerable#map in this case. Commented Jul 4, 2016 at 18:00
  • Thank you for the suggestions! Commented Jul 5, 2016 at 0:48

1 Answer 1

5

This sort of thing is easiest done with map, like so:

new_array = old_array.map{|s| s.split.uniq }

Details

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Everyone learning Ruby should spend some time looking through the multitude of methods available in the Enumerable library as many of these are extremely handy. map is one such method, but there are dozens of others.
Thank you so much for the tip about map!

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.