Variables and types

Numbers, strings, symbols, true / false, nil, and converting with to_i, to_f, to_s and Integer().

Runs in Zerethon IDE · Ruby 4.0 Official Ruby documentation ↗

A variable is created by assigning to it. Every value is an object with a class, which .class shows.

main.rb
count = 3          # Integer
price = 9.5        # Float
name = "Ada"       # String
ready = true       # true
nothing = nil      # nil
status = :active   # Symbol

puts [count.class, price.class, name.class, ready.class, nothing.class, status.class].join(" ")
puts "#{"42".to_i + 1} #{"2.5".to_f * 2} #{7.to_s + "7"}"
puts [7 / 2, 7.0 / 2, 7 % 2, 2**10].join(" ")
puts "#{"abc".to_i} #{nothing.nil?} #{Integer("42")}"

Output

Integer Float String TrueClass NilClass Symbol
43 5.0 77
3 3.5 1 1024
0 true 42
  • Integer division truncates: 7 / 2 is 3. Write 7.0 / 2 or 7.fdiv(2) for 3.5.
  • "abc".to_i quietly gives 0; Integer("abc") raises an ArgumentError — use it when bad input should be noticed.
  • Only nil and false are false in a condition. 0 and "" are true.
  • A symbol such as :active is a fixed name, often used as a hash key.

Related topics

Official references