Variables and types
Ruby is dynamically typed: a variable is just a name pointing at an object, and the object knows its own type. You never declare types, but every value still has one, and Ruby is strict about mixing them.
Variables
- Names start with a lowercase letter or
_and usesnake_case. - A name that starts with a capital letter is a constant: Ruby warns if you reassign it.
The basic types
| Type | Examples | Notes |
|---|---|---|
Integer |
42, -7, 1_000_000 |
Unlimited size. _ makes big numbers readable |
Float |
3.14, 2.5e3 |
Decimals, about 15 digits of precision |
String |
"hi", 'hi' |
Text, changeable |
Symbol |
:name, :pending |
Lightweight names (see below) |
true / false |
The only booleans | |
nil |
"No value" | |
Range |
1..10, 1...10 |
.. includes the end, ... excludes it |
Array / Hash |
[1, 2], { a: 1 } |
Collections (next lessons) |
Numbers
As in most languages, 0.1 + 0.2 isn't exactly 0.3 in binary floating point. For money, use whole cents or BigDecimal.
Strings
- Double quotes support interpolation
#{}and escapes like\n; single quotes are literal. str[0],str[0, 3](start, length) andstr[-8..](a range) slice strings.- Methods ending in
!change the object itself:s.upcase!modifiess;s.upcasereturns a new string.
Symbols
A symbol (:pending) is a name that's always the same object. Symbols are used for hash keys, method names and fixed choices, where you'd use an enum in other languages:
Two "paid" strings are separate objects; :paid is always the same one, which makes symbols fast to compare.
nil and truthiness
In conditions, only false and nil are false. Everything else is true, including 0, "" and []:
&. (the "safe navigation" operator) and || for defaults are how Ruby code handles missing values without crashing.
Converting between types
Ruby never converts automatically, so mixing types is an error:
Convert explicitly, or use interpolation, which calls to_s for you:
"12abc".to_i quietly gives 12 and "abc".to_i gives 0. When the input must be a valid number, use Integer("…") or Float("…"), which raise an error instead.
Checking types
Ruby programmers rarely check types. They care whether an object responds to the method they need ("duck typing": if it quacks like a duck…).
Practice
- Store a price in cents (
1999) and print it as₹19.99using/and%. - Ask for a number with
gets, convert it safely withInteger(), and print whether it's even. - Print which of these are truthy:
0,"false",nil,[]. - Turn
"hello world from ruby"into"Hello World From Ruby".
1.What does 7 / 2 give in Ruby?
2.Which values are falsy in Ruby?
3.What happens with "Age: " + 31?
4.What's special about a symbol like :paid?