A way of storing lists in Ruby
names = ["Faisal", "Sara", "Jane"]
An array can store a mix of data types.
arr = [[1, 2], "Yo", 1, 21, true, [1, 2, 3]]
puts arr[0][0] # outputs: 1
Real-life Analogy: Tennis balls pack
A way of storing key-value pairs
person = {name: "Faisal", age: 24, "hobbies": ["Tennis", "Soccer"]}
Real-life Analogy: Drawers with labels
old syntax: person = {:name => "Faisal", :age => 24}
Hash keys must be either Symbols or Strings. Values can be anything (Strings, Arrays, Hashes)
List of people, with each person containing attributes about them
people = [
{name: "Faisal", age: 24, "hobbies": ["Tennis", "Soccer"]},
{name: "Sara", age: 29, "hobbies": ["Basket Ball"]}
]
X, Y points in a graph
data_points = [[2, 1], [3, 2], [4, 1]]
Keep track of a person (name, number) AND their home and mobile numbers.
person = {
name: "Faisal",
city: "Toronto",
phone_numbers: {mobile: "6479978509", home: "2892324545"}
}
Let's say we have the following array
people = [
{name: "Faisal", age: 24, "hobbies": ["Tennis", "Soccer"]},
{name: "Sara", age: 29, "hobbies": ["Basket Ball"]}
]
Get the name of the first friend
people[1][:name] # outputs: Sara
Retrieve the names of all people in an Array
people_names = []
people.each do |person|
people_names = person[:name]
end
You can accomplish the same using a fancier method called #map
people_names = people.map {|person| person[:name]}
Symbols and Strings store the same type of data (lists of characters, a.k.a words). Hash keys can be either Strings or Symbols.
Symbols are a more efficient way of storing a string. You can read more about the details here: http://www.reactive.io/tips/2009/01/11/the-difference-between-ruby-symbols-and-strings/
Ruby Docs: http://ruby-doc.org/
Use the search bar.
Take a look at docs for Enumerable, Array, Hash.
Use instance variables to share variables accross different methods. Instance variables start with a @
character.
# File called friends.rb
require_relative('./friends')
# above line is the equivalent of copy/pasting the code in a file called friends.rb into the current file
def friend_names
friend_names = []
# friends is out of scope if it is not defined as an instance variable
@friends.each do |friend|
friend_names << friend[:name]
end
# return a list of friends' names
friend_names
end
def show_friend_names
puts "The friend names are"
puts friend_names
end
show_friend_names
# friends.rb file
@friends = [
{name: "Faisal", age: 24, "hobbies": ["Tennis", "Soccer"]},
{name: "Sara", age: 29, "hobbies": ["Basket Ball"]}
]