Ruby/Number/Fixnum extension

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Add double_upto method to Fixnum

class Fixnum
  def double_upto(stop)
    x = self
    until x > stop
      yield x
     x = x * 2
    end
  end
end
10.double_upto(50) { |x| puts x }
# 10
# 20
# 40



Calculating a factorial in Ruby

class Fixnum
  def factorial
    (1..self).inject { |a, b| a * b }
  end
end
puts 8.factorial



NoMethodError: undefined method "new" for Fixnum:Class

puts 100.object_id                                # => 201
puts (10 * 10).object_id                          # => 201
Fixnum.new(100)



redefine basic arithmetic

class Fixnum 
    alias old_plus + 
    # Redefine addition of Fixnums. This is a BAD IDEA! 
    def +(other) 
        old_plus(other).succ 
    end 
end



Simulating a Subclass of Fixnum

require "delegate"
class HexNumber < DelegateClass(Fixnum)
  # The string representations of this class are hexadecimal numbers.
  def to_s
    sign = self < 0 ? "-" : ""
    hex = abs.to_s(16)
    "#{sign}0x#{hex}"
  end
  def inspect
    to_s
  end
end
HexNumber.new(10)                             # => 0xa
HexNumber.new(-10)                            # => -0xa
HexNumber.new(1000000)                        # => 0xf4240
HexNumber.new(1024 ** 10)                     # => 0x10000000000000000000000000
HexNumber.new(10).succ                        # => 11
HexNumber.new(10) * 2                         # => 20