Ruby/Language Basics/Math Operators

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

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

Содержание

Abbreviated Assignment Operators

x = 5
x = x + 1
# or the abbreviated way:
x += 1



A few of Ruby"s assignment operators

x = 12 # assignment
puts x += 1 # abbreviated assignment add
puts x -= 1 # abbreviated assignment subtract
puts x *= 2 # abbreviated assignment multiply
puts x /= 2 # abbreviated assignment divide



be careful when you use the div method

puts 24.div 2
puts (25.0).div(2.0)



Division and Truncation

# When you do integer division in Ruby, any fractional part in the result will be truncated.
puts 24 / 2 # no problem
puts 25 / 2 # uh-oh, truncation
puts 25.0 / 2 # using a float as at least one operand solves it
puts 25.0 / 2.0 # same when both operands are floats



get acquainted with math operations in Ruby

puts 3 + 4 # add
puts 7 - 3 # subtract
puts 3 * 4 # multiply
puts 12 / 4 # divide
puts 12**2 # raise to a power (exponent)
puts 12 % 7 # modulo (remainder)



methods such as div, modulo, divmod, quo, and remainder.

puts 24.div 2 # division
puts (25.0).div(2.0) # result is integer
puts 12.modulo 5 # modulo
puts 12.modulo(5.0) # modulo with float
puts 12.divmod 5 # return array with quotient, modulus
puts 12.0.divmod 5.0 # with float
puts 12.quo 5 # return the quotient
puts 12.remainder 5 # return the remainder



note Ruby does not have ++

x = 1
x += 1          # Increment x: note Ruby does not have ++.
y -= 1          # Decrement y: no -- operator, either.



Some of the operators have assignment shortcuts

# value = value + 3
# can be made shorter with the += addition assignment operator, like this:
# value += 3
 
value = 3
puts value
value += 3   #addition
puts value
value /= 2   #division
puts value
value *= 3   #multiplication
puts value
value **= 2  #exponentiation
puts value



unary operators, + and -, which indicate negative and positive numbers

puts +7 + -5
puts -20 + 32
puts -20 - +32
puts 20 * -8



Using Math Operators

value = 3
puts value
value = value + 3   #addition
puts value
value = value / 2   #division
puts value
value = value * 3   #multiplication
puts value
value = value ** 2  #exponentiation
puts value