Can't modify frozen Fixnum on Ruby 2.0 -
i have following code:
require 'prime' class numeric #... math helpers def divisors return [self] if self == 1 @divisors ||= prime_division.map |n,p| (0..p).map { |i| n**i } end.inject([1]) |a,f| a.product(f) end.map { |f| f.flatten.reduce(:*) } - [self] end def divisors_sum @divisors_sum ||= divisors.reduce(:+) end #... more methods evaluate code , 'caches' , assigns (||=) instance variables end
wich outputs error with:
> 4.divisors /home/cygnus/projects/project-euler/stuff/numbers.rb:24:in `divisors_sum': can't modify frozen fixnum (runtimeerror)
the error disappears when remove caching instance variables @divisors
, @divisors_sum
... etc. , happens on ruby 2.0. ran on 1.9.3 without issues. what's happenning?
@divisors
instance variable on instance of fixnum, trying alter it. shouldn't doing this.
what this?
module divisors def self.for(number) @divisors ||= { } @divisors[number] ||= begin case (number) when 1 [ number ] else prime_division.map |n,p| (0..p).map { |i| n**i } end.inject([1]) |a,f| a.product(f) end.map { |f| f.flatten.reduce(:*) } - [ number ] end end end def self.sum(number) @divisors_sum ||= { } @divisors_sum[number] ||= divisors(number).reduce(:+) end end class numeric #... math helpers def divisors divisors.for(self) end def divisors_sum divisors.sum(self) end end
this means methods in numeric not modify instance, cache stored elsewhere.
Comments
Post a Comment