Use the each
method of Array to iterate over [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
, and print out each value.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# one line version
arr.each { |number| puts number }
# multi-line version
arr.each do |number|
puts number
end
Video Walkthrough
Same as above, but only print out values greater than 5.
# one line version
arr.each { |number| puts number if number > 5 }
# multi-line version
arr.each do |number|
if number > 5
puts number
end
end
Video Walkthrough
Now, using the same array from #2, use the select
method to extract all odd numbers into a new array.
# one line version
new_array = arr.select { |number| number % 2 != 0 }
# multi-line version
new_array = arr.select do |number|
number % 2 != 0
end
Video Walkthrough
Append 11
to the end of the original array. Prepend 0
to the beginning.
# Append
arr.push(11)
# --- or ---
arr << 11
# Prepend
arr.unshift(0)
Video Walkthrough
Get rid of 11
. And append a 3
.
# Remove from end of array
arr.pop
# Append
arr << 3
# --- or ---
arr.push(3)
Video Walkthrough
Get rid of duplicates without specifically removing any one value.
# Does not modify calling object
arr.uniq
# Modifies the calling object
arr.uniq!
Video Walkthrough
What's the major difference between an Array and a Hash?
The major difference between an array and a hash is that a hash contains a key value pair for referencing by key.
Video Walkthrough
Create a Hash, with one key-value pair, using both Ruby syntax styles.
hash = {:name => 'bob'} # <= old version
hash = {name: 'bob'} # <= new version
Video Walkthrough
Suppose you have a hash h = {a:1, b:2, c:3, d:4}
1. Get the value of key `:b`.
2. Add to this hash the key:value pair `{e:5}`
3. Remove all key:value pairs whose value is less than 3.5
1. h[:b]
2. h[:e] = 5
3.
# one line version
h.delete_if { |k, v| v < 3.5 }
# multi-line version
h.delete_if do |k, v|
v < 3.5
end
Video Walkthrough
Can hash values be arrays? Can you have an array of hashes? (give examples)
Yes
# hash values as arrays
hash = {names: ['bob', 'joe', 'susan']}
# array of hashes
arr = [{name: 'bob'}, {name: 'joe'}, {name: 'susan'}]
Video Walkthrough
Given the following data structures, write a program that copies the information from the array into the empty hash that applies to the correct person.
contact_data = [["joe@email.com", "123 Main st.", "555-123-4567"],
["sally@email.com", "404 Not Found Dr.", "123-234-3454"]]
contacts = {"Joe Smith" => {}, "Sally Johnson" => {}}
# Expected output:
# {
# "Joe Smith"=>{:email=>"joe@email.com", :address=>"123 Main st.", :phone=>"555-123-4567"},
# "Sally Johnson"=>{:email=>"sally@email.com", :address=>"404 Not Found Dr.", :phone=>"123-234-3454"}
# }
contacts["Joe Smith"][:email] = contact_data[0][0]
contacts["Joe Smith"][:address] = contact_data[0][1]
contacts["Joe Smith"][:phone] = contact_data[0][2]
contacts["Sally Johnson"][:email] = contact_data[1][0]
contacts["Sally Johnson"][:address] = contact_data[1][1]
contacts["Sally Johnson"][:phone] = contact_data[1][2]
Video Walkthrough
Using the hash you created from the previous exercise, demonstrate how you would access Joe's email and Sally's phone number.
puts "Joe's email is: #{contacts["Joe Smith"][:email]}"
puts "Sally's phone number is: #{contacts["Sally Johnson"][:phone]}"
Video Walkthrough
Use Ruby's Array method delete_if
and String method start_with?
to delete all of the strings that begin with an "s" in the following array.
arr = ['snow', 'winter', 'ice', 'slippery', 'salted roads', 'white trees']
Then recreate the arr
and get rid of all of the strings that start with "s" or start with "w".
arr.delete_if { |str| str.start_with?("s") }
arr.delete_if { |str| str.start_with?("s", "w") }
Video Walkthrough
Errata:
word
where the above solution uses str
.
Take the following array:
a = ['white snow', 'winter wonderland', 'melting ice',
'slippery sidewalk', 'salted roads', 'white trees']
and turn it into a new array that consists of strings containing one word. (ex. ["white snow", etc...]
→ ["white", "snow", etc...]
. Look into using Array's map
and flatten
methods, as well as String's split
method.
a = ['white snow', 'winter wonderland', 'melting ice',
'slippery sidewalk', 'salted roads', 'white trees']
a = a.map { |pairs| pairs.split }
a = a.flatten
p a
Video Walkthrough
What will the following program output?
hash1 = {shoes: "nike", "hat" => "adidas", :hoodie => true}
hash2 = {"hat" => "adidas", :shoes => "nike", hoodie: true}
if hash1 == hash2
puts "These hashes are the same!"
else
puts "These hashes are not the same!"
end
These hashes are the same!
Video Walkthrough
Challenge: In exercise 11, we manually set the contacts
hash values one by one. Now, programmatically loop or iterate over the contacts
hash from exercise 11, and populate the associated data from the contact_data
array. Hint: you will probably need to iterate over ([:email, :address, :phone]
), and some helpful methods might be the Array shift
and first
methods.
Note that this exercise is only concerned with dealing with 1 entry in the contacts
hash, like this:
contact_data = ["joe@email.com", "123 Main st.", "555-123-4567"]
contacts = {"Joe Smith" => {}}
As a bonus, see if you can figure out how to make it work with multiple entries in the contacts
hash.
Exercises marked as challenges can be very difficult. Don't get discouraged if you can't complete it, but do make the attempt. Even if you can't solve the exercise, be sure to read through the solution, if one is provided.
contact_data = ["joe@email.com", "123 Main st.", "555-123-4567"]
contacts = {"Joe Smith" => {}}
fields = [:email, :address, :phone]
contacts.each do |name, hash|
fields.each do |field|
hash[field] = contact_data.shift
end
end
Solution to bonus, where we can work with multiple entries in the contacts
hash:
contact_data = [["joe@email.com", "123 Main st.", "555-123-4567"],
["sally@email.com", "404 Not Found Dr.", "123-234-3454"]]
contacts = {"Joe Smith" => {}, "Sally Johnson" => {}}
fields = [:email, :address, :phone]
contacts.each_with_index do |(name, hash), idx|
fields.each do |field|
hash[field] = contact_data[idx].shift
end
end
Video Walkthrough