Ruby Arrays
# Ruby Arrays
# In our programs we will have to deal with structured lists of data
# For that in Ruby we use the Array class.
# Arrays being lists, it's natural to want to go through each
# item in the list. We call this array traversal or iteration.
numbers = [ "One", 2, "Three" ]
puts numbers
# array
numbers = [ "One", 2, "Three" ]
# We can use for to iterate the collection:
for element in numbers
puts "-> #{element}"
end
# This approach is not used too much. It is much more common to see:
numbers.each do |element|
puts "--> #{element}"
end
# Of course we can modify or mutate our arrays by adding and removing elements.
# To add elements we can use the shovel operator << or push function.
# To remove elements we can, for example, use the delete_at function.
my_array = []
my_array << "A"
my_array.push "B"
my_array.push "C"
my_array.delete_at 2
puts my_array
------
arr.each {|something| puts something.class}
arr.push {'saddd', 'saddd', 'saddd', 'saddd'}
class Item
def price
return '3.50'
end
end
arr.push {'Item.new', 'Item.new', 'Item.new', 'Item.new'}
----------------
# Hashes
# A Hash is an associative array.
# Whereas elements in an array have an order or number associated to them,
# elements in a hash have a name associated to them.
# It's basically like a dictionary. You can lookup values by its name or key.
my_hash = {}
my_hash["AST"] = "Asturias"
my_hash[2] = "Galicia"
puts my_hash["AST"]
puts my_hash[2]
puts my_hash
# While
#The while is a construct that runs a chunk of code until a condition is false.
string = ""
# While the string's length is less than 10
while string.size < 10
# Add an 'a'
string = string + 'a'
end
puts "The final string is #{string}"
# Enumerables
# Almost all Ruby collections include a mixin called Enumerable.
# This is used to provide traversal and searching methods
# http://ruby-doc.org/core-2.1.2/Enumerable.html