Search code examples
rubyundefinednomethoderror

Undefined method when trying to square each element in array


I am trying to write a method called square_digits that squares every digit in a given number. I wrote:

def square_digits(num)
  number_array = num.to_s.split("")
  num_to_int = number_array.to_i
  num_squared = num_to_int.each{|n| n**2}
  return num_squared.join("")
end

When trying to run square_digits(3212), which should return 9414, I get the following error message:

`block in square_digits': undefined method `**' for "3":String (NoMethodError)
from `each'
from  `square_digits'
from  `
'

I'm not quite sure what I should do to fix it; any suggestions?


Solution

  • Hmm there are a few problems here:

    With the input 123 it should error on:

    num_to_int = number_array.to_i
    

    With:

    NoMethodError: undefined method 'to_i' for ["1","2","3"]:Array

    You want:

    num_to_int = number_array.map(&:to_i)
    

    Also

    num_squared = num_to_int.each{|n| n**2}

    doesn't return the results of each just the original array.

    So with the first fix it will just return "123"

    you want:

    num_squared = num_to_int.map{|n| n**2}
    

    So the final function looks like:

    def square_digits(num)
      number_array = num.to_s.split("")
      num_to_int = number_array.map(&:to_i)
      num_squared = num_to_int.map{|n| n**2}
      return num_squared.join("")
    end
    

    Although i'm confused about what you are trying to achieve.