Ciaran S Ciaran S - 2 months ago 7
Ruby Question

Ruby - Separate out the first two digits from integer of increasing length

I keep getting the error below when running my code.

My Code:

class Integer
def num_digits
Math.log10(self).to_i + 1
end

def p(t)
case t
when 3
return self * (self + 1) / 2
when 4
return self**2
when 5
return self * ((3 * self) - 1) / 2
when 6
return self * ((2 * self) - 1)
when 7
return self * ((5 * self) - 3) / 2
when 8
return self * ((3 * self) - 2)
end
end
end

$p3 = [], $p4 = [], $p5 = [], $p6 = [], $p7 = [], $p8 = []
$polygonals = [$p3, $p4, $p5, $p6, $p7, $p8]

(3..8).each_with_index do |t, index|
i = 1
until i == 150
$polygonals[index] << i.p(t)
i += 1
end
end

$polygonals.each { |array| array.reject! { |x| x.num_digits != 4 } }


Error:

`block (2 levels) in <main>': undefined method `num_digits' for []:Array (NoMethodError)


However, if I change the last line of code to:

$polygonals.each { |array| array.each { |x| x.reject! { |y| y.num_digits != 4 } } }


I get the error:

`block (2 levels) in <main>': undefined method `reject!' for 1:Fixnum (NoMethodError)


How can
x
be type
array
in the first case and type
Fixnum
in the second?

Answer

The commas on this line

 $p3 = [], $p4 = [], $p5 = [], $p6 = [], $p7 = [], $p8 = []

Don't do what you think. In ruby

 a = 1,2

sets a to [1,2], so this is setting $p3 to

 [[], [], [], [], [], []]

If you put those assignments on separate lines or use ; rather than commas then those variables will be initialised to what you expect.