2.8 KiB
Vendored
2.8 KiB
Vendored
mruby-numeric-ext
Purpose
This mrbgem extends the Numeric and Integer classes in mruby with additional methods for common numerical operations and checks.
Functionality
This gem adds the following methods:
Numeric Class
zero?: Returnstrueif the number is zero,falseotherwise.nonzero?: Returns the number itself if it's not zero,nilotherwise.positive?: Returnstrueif the number is greater than 0,falseotherwise.negative?: Returnstrueif the number is less than 0,falseotherwise.integer?: Returnstrueif the number is anInteger(this is overridden in theIntegerclass).
Integer Class
allbits?(mask): Returnstrueif all bits ofself & maskare 1.anybits?(mask): Returnstrueif any bits ofself & maskare 1.nobits?(mask): Returnstrueif no bits ofself & maskare 1.bit_length: Returns the number of bits of the absolute value ofselfin binary.0.bit_length #=> 0;(-1).bit_length #=> 0;2.bit_length #=> 2.ceildiv(other): Returns the result ofselfdivided byother, rounded up to the nearest integer.integer?: Returnstrue(overridesNumeric#integer?).remainder(numeric): Returns the remainder ofselfdivided bynumeric. Equivalent tox - y * (x / y).truncate.pow(numeric): Returnsselfraised to the power ofnumeric.pow(integer, integer): Returns modular exponentiation ((self ** exponent) % modulus).digits(base=10): Returns an array of integers representing the base-radix digits ofself. The first element is the least significant digit.size: Returns the number of bytes in the machine representation of the integer.odd?: Returnstrueif the integer is odd,falseotherwise.even?: Returnstrueif the integer is even,falseotherwise.Integer.sqrt(integer): (Class method) Returns the integer square root of the given non-negative integer.
How to use
To use this mrbgem, add it to your build_config.rb:
MRuby::Build.new do |conf|
# ... (other configurations)
conf.gem :core => 'mruby-numeric-ext'
end
Then you can use the extended methods:
p 5.positive? # => true
p (-3).negative? # => true
p 0.zero? # => true
p 5.nonzero? # => 5
p 0.nonzero? # => nil
p 7.allbits?(3) # => false (binary 111 & 011 is 011, not 011)
p 7.anybits?(3) # => true
p 7.nobits?(8) # => true (binary 111 & 1000 is 000)
p 10.ceildiv(3) # => 4
p (-10).ceildiv(3) # => -3
p 10.remainder(3) # => 1
p (-10).remainder(3) # => -1
p 2.pow(3) # => 8
p 2.pow(3, 5) # => 3 ( (2**3) % 5 )
p 12345.digits # => [5, 4, 3, 2, 1]
p 12345.digits(16) # => [9, 3, 0, 3]
p 42.size # => (depends on machine, e.g., 4 or 8)
p 5.bit_length # => 3
p 5.odd? # => true
p 4.even? # => true
p Integer.sqrt(16) # => 4
p Integer.sqrt(17) # => 4