rfish26535
rfish26535

Reputation: 459

"nil can't be coerced into Fixnum" unexpected error

I'm writing a small Ruby algorithm that throws the above error only on values ending with "1", like "21", "31", "41".

success = []
(1..9_999_999).each do |num|
  num_s = num.to_s.split("")
    if num_s.inject(0){ |memo, val| memo += (1..val.to_i).inject(&:*) } == num
      success << []
    end
end

What's bizarre is that there are no errors for the main line of code by itself:

["2", "1"].inject(0){ |memo, val| memo += (1..val.to_i).inject(&:*) } #-> 3 

Based on the error, I thought there might be something problematic with doing:

(1.."1".to_i).inject(&:*) #-> 1

But there is not... I'm confused.

Upvotes: 0

Views: 1409

Answers (1)

falsetru
falsetru

Reputation: 368954

>> ["1", "0"].inject(0){ |memo, val| memo += (1..val.to_i).inject(&:*) } #-> 3
TypeError: nil can't be coerced into Fixnum
        from (irb):2:in `+'
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `each'
        from (irb):2:in `inject'
        from (irb):2
        from C:/Ruby200-x64/bin/irb:12:in `<main>'

Above error occured because: (1..0).inject(&:*) return nil.

>> (1..0).inject(&:*)
=> nil
>> 0 * (1..0).inject(&:*)
TypeError: nil can't be coerced into Fixnum
        from (irb):4:in `*'
        from (irb):4
        from C:/Ruby200-x64/bin/irb:12:in `<main>'

Upvotes: 1

Related Questions