Collections and Loops
Ruby collection (map, list, array) and loops (for, each, while)
Collection and Loops
Ruby has many default collection types that provide quite a bit of functionality to get you started. There is some shorthand and longhand techniques for iterating over collections that make it easier to have cleaner code.
Collections
The main collections in Ruby are Arrays
and Maps/Hashes
. Arrays
are used for linear ordered lists, while Hashes
are used name / value pairs and are unordered by nature. Both have similar named iteration methods that make using either very convenient. Both have a long and short way of creating the initial collection as well.
Example Array creation:
my_array = Array.new # longhand
my_array = [] # shorthand
# add an element
my_array << "value" # short hand
my_array.push "value" # long hand
# delete an element
my_array.delete "value" # by value
my_array.delete_at 0 # by index
Example Hash creation:
my_hash = Hash.new # longhand
my_hash = {} # shorthand
# add an element
my_hash['key'] = "value"
# delete an element
my_array.delete 'key'
Loops
General loop constructs are for
, while
, each
. Each of these provides a different reason for use. While
is used when you need to run a loop with a set condition for breaking the loop. For
is mostly used in the case of a certain range of items that need to be looped over. Each
is primarily used for iterating over a collection.
Within each type of loop there is the keywords break
and next
. Next
skips the rest of the loop logic and moves to the next item in the loop. Break
will exit out of the loop, this is handy for non-recoverable errors.
Example while
:
running = true
while running do
connection = nil # ... connection creation / usage
if !connection
running = false
end
end
Example for
:
for i in 0..10
puts " procesing #{i}"
if i % 2 == 0
next
end
end
The basic looping for a collection is an each
, after that there is a variety of specific looping options based on what you need to get done with the elements in the collection. Most iteration methods take a block / closure to facilate the specific item logic.
Example each
on an Array:
# shorthand
my_array = ['one', 'two', 'three']
my_array.each { |item| puts item }
# longhand
my_array = Array.new(['one', 'two', 'three'])
my_array.each do |item|
puts item
end
Example each
on an Hash:
# shorthand
my_hash = { one: 'one', two: 'two', three: 'three' }
my_hash.each { |key,value| puts key }
# longhand
my_hash = Hash.new({ one: 'one', two: 'two', three: 'three' })
my_hash.each do |key,value|
puts key
end
Next: String Manipulation