0

I have been given an assignment to take each number in an array, square it, and return it using the each method (specifically not collect, map, or inject). My code is below,

def square_array(array)
  array.each do |number|
    new_number = number ** 2
    new_array = []
    new_array.push (new_number)
    return new_array
  end
end

but this only returns one number, not each number in an array. Any thoughts on how to do this?

2 Answers 2

3

The reason your code will not work is because each time you loop to a number in array, you create a new array, add the square of the number to your new array, and then return out of your function! There are two issues here. First off, you need to create the new array before eaching through array. Secondly, it's important to not return out of your function until you have looped through all of the numbers in array. In your current function, you will only ever loop through the first element of array, and then return out of the square_array function.

def square_array(array)
  new_array = []  
  array.each { |number| new_array << number ** 2 } # Shorthand syntax for a do-block
  new_array # Return keyword is not necessary in the last line of a method
end
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! But what is <<? All I can find on Google is that it's a Binary Left Shift Operator. (The left operands value is moved left by the number of bits specified by the right operand.) How does that work in this context? Thanks again!
<< is the shovel operator. It appends to the end of the array. Check out the docs: ruby-doc.org/core-2.2.0/Array.html#method-i-3C-3C
Thanks, that's helpful. Could you also replace that line with the following? 'array.each { |number| new_array.push (number ** 2) }'
You can also use new_array.push(number ** 2), but this is shorter!
1
def square_array(array)
  array.each_with_object([]) do |number, new_array|
    new_array << number ** 2
  end
end

Comments

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.