ashleigh090990
ashleigh090990

Reputation: 63

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?

Upvotes: 1

Views: 1210

Answers (2)

Gagan Gami
Gagan Gami

Reputation: 10251

You can also try this ;)

def square_digits(num)
  num.to_s.split('').map { |n| n.to_i ** 2 }.join("")
end

Or

def square_digits(num)
  num.to_s.chars.map { |n| n.to_i ** 2 }.join("")
end

Upvotes: 0

DickieBoy
DickieBoy

Reputation: 4956

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.

Upvotes: 3

Related Questions