AnyCompiler

Variables and Types

Creating a Ruby variable is just an assignment — x = 5. There is no let, var, my, def, or type annotation of any kind; the first assignment to a name brings it into existence. This is more minimal than every other language on this site: even Perl requires a sigil and Python requires nothing-but-a-name-with-no-sigil-at-all is actually the closest comparison — but Python, unlike Ruby, still has no method-call surface on its ints, so the similarity is only skin deep.

Ruby is dynamically typed: a variable has no declared type, only whatever object it currently points to. .class asks any object what it actually is right now.

x = 5
y = 3.14
name = "Ruby"
is_fun = true
nothing = nil

puts x.class
puts y.class
puts name.class
puts is_fun.class
puts nothing.class

x = "now I'm a string"
puts x.class
Output
Integer
Float
String
TrueClass
NilClass
String

The same name x held an Integer and then, after reassignment, a String — nothing about the variable itself ever had a fixed type to violate. true and false are each the sole instance of their own class (TrueClass, FalseClass), and nil is the sole instance of NilClass — all genuinely objects, not special-cased primitives. Next: strings — interpolation, concatenation, and common string methods.

Practice exercise

Set x = 5 and print its class, then reassign x to the string "now a string" and print its class again.