Search code examples
arraysrubymethodssquare

How to square an array of numbers in ruby with while without `each` `map` or `collect` methods?


I'm new to coding in RUBY. I'm trying to write a method that squares each element in an array of numbers and returns a new array of these numbers squared. Trying to use while loop and NOT use each, collect, or map. Having trouble understanding how to index/loop each individual element of array and square is (**).

This is what makes sense to me but I know its wrong.

def square_array(numbers)
  count = 0
  while count < numbers.length do
    numbers.index ** 2 
  end
  square_array(numbers)
end 

Will anyone please help me? Thanks!


Solution

  • The easy way to do it is map, of course:

    def square_array(numbers)
        numbers.map { |e| e ** 2 }
    end 
    

    But here's what you have to do to do the same with a while loop (which is good practice).

    1. Create an array to contain the transformed data.
    2. Create a counter (you've done that).
    3. Set up your while loop (as you have it, except you don't need the do at the end).
    4. Write a statement that squares the array element whose index is the same as your counter, and pushes that result into the array you created in step 1.
    5. Increment your counter by 1 (you forgot to do that, so you'll be getting an endless loop since count will always equal zero).
    6. Return the array you created in step 1.

    That will do it for you! See if you can put that together, rather than me just giving you the code.