Ruby/Number/Fixnum class

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

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

Содержание

Extend the Fixnum class with some helper methods to make manipulating dates easier

class Fixnum
  def seconds
    self
  end
  def minutes
    self * 60
  end
  def hours
    self * 60 * 60
  end
  def days
    self * 60 * 60 * 24
  end
end
puts Time.now
puts Time.now + 10.minutes
puts Time.now + 16.hours
puts Time.now - 7.days



find out the ancestors of Fixnum

p Fixnum.ancestors # => [Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel]



Fixnum literal value

123456                   => 123456   # Fixnum
0d123456                 => 123456   # Fixnum
123_456                  => 123456   # Fixnum - underscore ignored
-543                     => -543     # Fixnum - negative number
0xaabb                   => 43707    # Fixnum - hexadecimal
0377                     => 255      # Fixnum - octal
-0b10_1010               => -42      # Fixnum - binary (negated)
123_456_789_123_456_789  => 123456789123456789 # Bignum



Normal-looking math equations when you use operator methods, such as +

Each line that follows is actually a valid call to the Fixnum + method
10 + 2 # => 12
10.+ 2 # => 12
(10).+(2) # => 12



Output the modules where Fixnum lives

p Fixnum.included_modules # => [Precision, Comparable, Kernel]



Raise ArgumentError from method

def Fixnum.random(min, max)
  raise ArgumentError, "min > max" if min > max
  return min + rand(max-min+1)
end
Fixnum.random(10, 20)                             # => 13
Fixnum.random(-5, 0)                              # => -5
Fixnum.random(10, 10)                             # => 10
Fixnum.random(20, 10)
# ArgumentError: min > max