this is my code.
class Dog attr_accessor :name attr_reader :breed, :age def initialize(name, breed, age) @name = name @breed = breed @age = age @distance_in_kms = [] end def walk(distance_in_kms) @distance_in_kms << {distance: distance_in_kms} end def walked_distance @walked_distance = @distance_in_kms.inject(0) {|sum, hash| sum + hash[:distance]} end def display_walks puts "#{@name} has had #{@distance_in_kms.length} walks and walked #{@walked_distance} kms today:" @distance_in_kms.each do |each_walk| puts "#{each_walk[:distance]} km" end end #overriding to_s to print a meaningful representation of a class def to_s return "Dog: breed-#{@breed} name-#{@name}" end end doggo = Dog.new("Roy", "Labrador", 8) doggo.walk(3) doggo.walk(5) doggo.walk(1) puts doggo.name = "Dang" puts doggo.breed doggo.display_walks The result I have is this
Dang Labrador Dang has had 3 walks and walked kms today: 3 km 5 km 1 km The expected value before kms should be 9, the sum of each walk in a day. Obviously, I have done something wrong with the walked_distance method. I was trying to pass the value of array @distance_in_kms into @walked_distance, but it didn't work, the return value was nil.But what can I do to fix the problem and get expected results? Thank you!!
:amount:distance, still doesn't work#{@walked_distance}string to#{walked_distance}. Instance variable from the method never was called in your code.