algorithm - Ruby - modifying classes -


i wrote simple method checks if number armstrong number. want modify default number class putting method. so, have code:

def is_an(number)     (number.to_s.split(//).map(&:to_i).inject{|x,y|x+y**(number.size-1)}) == number ? true : false end p is_an(153) 

i want use method: 153.is_a? so, how this?

class number    def is_an       ??? how use object data on here? ???    end end 

thx lot reading.

incorporating @mikej's answer, plus replacing number self:

class fixnum   def is_an     digits = self.to_s.split(//).map(&:to_i)     digits.inject(0) { |x,y| x+y**digits.size } == self   end end 

but suggest name change, make more ruby like. instead of #is_an, isn't descriptive, how #armstrong? can call:

153.armstrong? 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -