0

Is there a way to return the new array? I try to return the array of squared value [1, 4, 9] but it keeps returning [1, 2, 3] (the original array) Here is my code:

def square_array(array)
  array.each do |number| 
    number *= number
    puts number
  end
end

square_array([1, 2, 3])
gregmarquet
  • 17
  • 1
  • 8
  • 1
    "...it keeps returning..." brought a smile to my face. I'm sure that everyone reading this has had the same thought: "Maybe if I just run it again it will work". – Cary Swoveland Dec 16 '15 at 05:19
  • Possible duplicate of [How to square each element of an array in Array class in Ruby?](http://stackoverflow.com/questions/16723386/how-to-square-each-element-of-an-array-in-array-class-in-ruby) – Gagan Gami Dec 16 '15 at 10:37

4 Answers4

1

A much simpler version that does what you want:

def square_array(array)
  array.map do |number|
    number*number
  end
end

The problem with your code is that when you assign something to number, you're just assigning a value to a local variable, not some magic reference into an array.

Linuxios
  • 34,849
  • 13
  • 91
  • 116
0

Try this out:

Using Each method

def square_array(array)
  temp = []
  array.each do |number| 
    temp <<  (number * number)
  end
  temp
end
Sachin Singh
  • 7,107
  • 6
  • 40
  • 80
  • Sachin, you can tighten this up by using [Enumerable#each_with_object](http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-each_with_object): `def square_array(array); array.each_with_object([]) { |number, temp| temp << (number * number) }; end`. – Cary Swoveland Dec 16 '15 at 05:27
  • @CarySwoveland, you are right but @gregmarquet just want to use `each` for his exercise. – Sachin Singh Dec 16 '15 at 06:16
  • You're right. Greg hasn't been on SO long so may be new to Ruby, in which case the use of `each_with_object` may be confusing. One possibility in such situations (when the code is short, as here) is to leave what you have then show the usual way the code would be written. – Cary Swoveland Dec 16 '15 at 21:48
0

When writing semantic ruby, it is best to use proper enumerable methods. There is no need for the temporary variable in this case... we can use the #map method to return a new array that is the result of applying a function to each value in turn. This is a core concept of the functional programming paradigm:

def square_array numbers
  numbers.map { |x| x ** 2 }
end
-1

I fund a way, I just needed to push the result in a new array

    def square_array(array)
      new_array = []
      array.each do |num|
        squared_num = num ** 2
        new_array.push(squared_num)
      end
      return new_array
    end
gregmarquet
  • 17
  • 1
  • 8
  • I really think you should consider `map` or even `map!` instead, as it does what you want and is more concise. – Makoto Dec 16 '15 at 04:24
  • I understand and appreciate the advice for the future, but I had to use .each for the purpose of the exercice. – gregmarquet Dec 16 '15 at 06:51