Ruby/Number/Integer

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

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

Содержание

An integer with the kind_of? method (this method is from the Object class).

# Integer honors the 0 (octal), 0b (binary), and 0x (hexadecimal) prefixes.
x = 100
 
x.kind_of? Integer # => true



Basic Math Operations for integer

puts 7 + 5 # add
puts 20 - 8 # subtract
puts 2 * 6 # multiply
puts 144 / 12 # divide
puts 12**2 # exponent
puts 12 % 5 # modulo (remainder of division)



Change x from an integer to a floating point with the to_f method from the Fixnum class

x = 100
x.to_f # => 100.0



Comparison Methods

puts 1 > 2
puts 1 < 2
# false
# true
puts 5 >= 5
puts 5 <= 4
# true
# false
puts 1 == 1
puts 2 != 1
# true
# true
puts "cat" < "dog"
# true



difference between "puts x / y" and "puts x.to_f / y.to_f"

x = 10
y = 3
puts x / y
 
puts x.to_f / y.to_f



General Predicates

puts 0.zero?        # => true (is this number zero?)
puts 1.0.zero?      # => false
puts 0.0.nonzero?   # => nil (works like false)
puts 1.nonzero?     # => 1 (works like true)
puts 1.integer?     # => true
puts 1.0.integer?   # => false
puts 1.scalar?      # => false: not a complex number. Ruby 1.9.
puts 1.0.scalar?    # => false: not a complex number. Ruby 1.9.



Integer and Float

# numbers without decimal points are called integers
# numbers with decimal points are usually called floating-point numbers, or more simply, floats.
# Here are some integers:
5
-205
9999999999999999999999999
0
# And here are some floats:
54.321
0.001
-205.3884
0.0



Integer is an instance of the Fixnum class, which inherits the Integer class.

x = 100
x.class # => Fixnum



Integer predicates

puts 0.even?        # => true (Ruby 1.9)
puts 0.odd?         # => false



List the modules which Integer class is from

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



puts 120.chr

puts 120.chr



to integers, using to_i:

puts 5.7.to_i