2

I'm a newbie to Ruby and I don't understand why do I have the result that I have.

  • I have a Person class in which I have the instance variables, @name, @age and @weight. In this class I override the to_s method to print the @name, @age and @weight of the object.
  • I have a House class in which I have an array of objects of type
    Person (@persons), and also I have a method called person that returns an object (in the position that is specified with the parameter number) in the array @persons, so for example, any_house_object.person(0) will return the first object of the array of objects of type Person that is on the any_house_object object.

    class Person
        def initialize(name, age, weight)
            @name = name
            @age = age
            @weight = weight
        end
    
        def to_s
            puts "Name: #{@name}"
            puts "Age: #{@age}"
            puts "Weight: #{@weight}"
        end
    end
    
    class House
        def initialize
            @persons = []
        end
    
        def add_person(name, age, weight)
            @persons << Person.new(name, age, weight)
        end
    
        def person(number)
            @persons[number]
        end
    end
    
    my_house = House.new
    
    my_house.add_person("Patrick", "18", "65")
    my_house.add_person("John", "18", "65")
    
    puts my_house.person(0)
    

This produce

    Name: Patrick
    Age: 18
    Wight: 65
    #<Person:0x5e2318>

Finally, my problem is that I don't understand why at the end, when I do puts my_house.person(0) also appears #<Person:0x5e2318> at the end.

Patricio Sard
  • 2,092
  • 3
  • 22
  • 52

1 Answers1

6

to_s is supposed to return a string, not output a string to the console. Your method needs to return the string you're building:

def to_s
  "Name: #{@name}\nAge: #{@age}\nWeight: #{@weight}"
end

Secondly, to_s is for converting an object to a string. You're not actually doing that anywhere. Just invoking puts <object> doesn't have anything to do with to_s.

If you want to output the string representation of your object, you either need...

puts my_house.person(0).to_s

Or, you need to also define a custom inspect method and use p <object> instead.

user229044
  • 232,980
  • 40
  • 330
  • 338