Created
September 23, 2018 12:29
-
-
Save harrisonmalone/c310198ee6aa50f0d71fb3226a7f7d1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Dog | |
attr_accessor :location | |
def initialize(name, age) | |
@name = name | |
@age = age | |
@location = location | |
@distance = 0 | |
@walks = 0 | |
@walk_data = [] | |
end | |
def walk(location, distance) | |
@location = location | |
@distance = distance | |
walk_hash = {location: location, distance: distance} | |
@walk_data << walk_hash | |
@walks += 1 | |
self | |
end | |
def display_walks | |
distance = @walk_data.map do |item| | |
item[:distance] | |
end | |
total_distance = distance.sum | |
puts "I have been for #{@walks} #{@walks == 1 ? "walk" : "walks"} today, which is a total of #{total_distance} kilometres" | |
puts "walk data" | |
display = @walk_data.each_with_index.map do |walk, index| | |
puts "#{index + 1}) location: #{walk[:location]} | distance: #{walk[:distance]}" | |
end | |
end | |
end | |
tilly = Dog.new("Tilly", 3) | |
beach_walk = tilly.walk("beach", 20) | |
park_walk = tilly.walk("park", 10) | |
around_the_block_walk = tilly.walk("around the block", 2) | |
p tilly.display_walks | |
# i think i understand class methods and `self` at a much better level now | |
# especially the doggo challenge, that reaffirmed my understanding, when you return self in an instance method you are literally returning that instance | |
# when you call `self` in a instance method name you are referring to literally the class itself | |
# even having the location and distance as new instance variables was nice as well, when we call that instance method on an instance we pass location and distance as parameters that we pass in the method call, this then allows us to pass new instance variables inside the instance method, we then passed those to the hash | |
# `yield` i'm still a little funny with but it's not really used so much, it's more just conceptually knowing that yield exits a function and you can then do stuff in a block you call the same name out of the function body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment