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 / 2is3. Write7.0 / 2or7.fdiv(2)for3.5. "abc".to_iquietly gives0;Integer("abc")raises anArgumentError— use it when bad input should be noticed.- Only
nilandfalseare false in a condition.0and""are true. - A symbol such as
:activeis a fixed name, often used as a hash key.