Search code examples
rubyenumerable

my enumerable line for narcissistic numbers


value is an integer and this is supposed to take each digit in value, raise it to the power of the number of digits in value, then sum them up.

For some reason, it works for everything but 370 and 371, at 370 i get 346 and 371 yields 347, whats going on here?!

value.to_s.chars.map {|e| e.to_i }
  .inject{|sum, e| sum += e ** value.to_s.length }

Solution

  • You are missing the initial value for inject. This will work:

     value.to_s.chars.map {|e| e.to_i }
       .inject(0){|sum, e| sum += e ** value.to_s.length }
    

    From the docs:

    If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo.