Hashes are basically like JavaScript objects. They are composed of key/value pairs and each key points to a specific value. For example;
a_hash = { name: "John", age: "20" }
a_hash[:age]
# => "20"
To access data from the hash above, bracket notation is used and the symbol for the key being accessed is passed in. It can also be used to assign a new value to a key:
a_hash[:age] = 25
a_hash
# => {:name=>"John", :age=>25}
Enumerable
Enumerable is a method that "enumerates" (goes one by one) over every element of a collection. Enumerables include:
- Map
- Times
- Each
- Collect
- Find
- Sum
Common Hash Methods
While bracket notation is used to access values in a hash, they can also be deleted using the delete method by passing in a key:
snacks = { crisps: true, flavor1: "salted", flavor2: "barbecue" }
snacks.delete(:flavor2)
snacks
# => {:crisps=>true, :flavor1=>"salted"}
It also has methods of accessing an array of the keys and an array of the values:
snacks.keys
# => [:crisps, :flavor1]
snacks.values
# => [true, "salted"]
It uses the empty method to check if there are no key-value pairs defined on the hash:
snacks.empty?
# => false
{}.empty?
# => true
It uses the merge method to join together multiple hashes:
more_flavors = { flavor2: "barbecue", flavor3: "salt and vinegar" }
snacks.merge(more_flavors)
# => {:crisps=>true, :flavor1=>"salted", :flavor2=>"barbecue", :flavor3=>"salt and vinegar"}
Enumerables:Common Methods
Include :
- each
- map/collect
- filter/ #select/#find_all
- find / #detect
- sort
EachMethod
Used To access each element of the array, but not interested in returning a new array Has the same functionality as foreach which is used in JS
new_array = ["this", "is", "Ruby"].each do |str|
puts str.upcase
end
"THIS"
"IS"
"RUBY"
MapMethod
Uses To access every element of an array, calculates the new value and returns the new values with the same length as the original array.
[1, 2, 3].map { |num| num * 2 }
# => [2, 4, 6]
users = [{ name: "Duane", phone: "555-555-5555"}, { name: "Liza", phone: "555-555-5556" }]
users.map do |user|
"Name: #{user[:name]} | Phone: #{user[:phone]}"
end
# => ["Name: Duane | Phone: 555-555-5555", "Name: Liza | Phone: 555-555-5556"]
[1, 2, 3].collect { |num| num * 2 }
# => [2, 4, 6]
FilterMethod
Uses To access every element of an array,check is it matches some condition, then returns a new array of all values that match Alias #select , #find_all
[1, 2, 3, 4, 5].filter { |num| num.even? }
# => [2, 4]
[1, 2, 3, 4, 5].filter { |num| num.odd? }
=> [1, 3, 5]
SortMethod
Uses Returns a new array where all elements have been sorted based on the criteria.
nums = [1, 5, 3]
sorted_nums = nums.sort
sorted_nums
# => [1, 3, 5]
find
Uses To access every element of an array, checks if it matches some criteria, then returns the first element that matches .
[1, 2, 3, 4, 5].find { |num| num.even? }
# => 2