Reading — step 1 of 5
Learn
~1 min readGetting Started
Standard arithmetic: + - * / %. Integer division when both operands are integers — 7 / 3 == 2. Mix in a float for a real result: 7.0 / 3 == 2.333….
a = 17
b = 5
puts a + b # 22
puts a / b # 3 (integer)
puts a.to_f / b # 3.4
puts a % b # 2
puts 2 ** 10 # 1024 (power)
Numbers in Ruby have rich method APIs:
5.times { |i| puts i } # 0 1 2 3 4
(1..3).each { |n| puts n } # 1 2 3
puts 17.divmod(5) # [3, 2] — quotient and remainder
puts 100.to_s(2) # "1100100" — binary
Integers in Ruby are arbitrary precision — 1_000_000 ** 100 works without overflow.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…