New Array on the Block
An Array is a container, which holds values in an ordered fashion.
(If you're using Mac OS X open up Terminal and type irb, then hit enter, to play along at home)
How to create a an Array
my_array = ['Ferrari', 'McLaren', 'Williams']
Get the value of an Array element
my_array[0]
Will return, "Ferrari"
my_array[1]
Will return, "McLaren"
my_array[2]
Will return, "Williams"
my_array.first
Will return, "Ferrari"
my_array.last
Will return, "Williams"
Arrays on the Block
A Block can loop through things. i.e:
my_array.each do |an_element|
puts an_element
end
Returns:
Ferrari
McLaren
Williams
Second Block Example
my_array.each {|an_element| puts an_element}
Returns:
Ferrari
McLaren
Williams
Block example with index
my_array.each_with_index do |an_element, index|
puts "#{an_element} is number: #{index}"
end
Returns:
Ferrari is number: 0
McLaren is number: 1
Williams is number: 2
Labels: code, ruby, rubyonrails
