Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)
Up and Down
We can call an object and then iterate over it up to our preference.
var = 15
var.upto(22) {|i| print "#{i} "}
⇩
15 16 17 18 19 20 21 22
The same principle applies for downto.
var = 15
var.downto(7) {|i| print "#{i} "}
⇩
15 14 13 12 11 10 9 8 7
Collect
We can use the collect method on an array and use the block on each element.
ary = [1,2,3,4]
ary.collect {|i| print "#{i + 10} "}
⇩
11 12 13 14
Symbols
Strings in Ruby have unique object ids. That's because each string is unique and precious. Strings can have the same value as other strings and exist as separate objects. Symbols on the other hand can't. There's only one copy of a symbol at a time. There can only be one Highlander!
Symbols begin with a colon ( : ) followed by a name that uses the standard variable naming conventions. Which means the following character must be either a letter or underscore. This also means that spaces between words must be replaced with underscores.
There's a method in ruby that allows us to check object ID numbers. Ruby uses these internally to distinguish between different objects. Type the following in your editor and run the file:
puts "I'm a string.".object_id
puts "I'm a string.".object_id
puts :im_a_symbol.object_id
puts :im_a_symbol.object_id
Notice that both instances of the strings have different ID numbers, while the symbols have the same ID number. We will talk more about symbols soon.