1

I've been trying to get this code to output:

'Mary has a pet called Satan.'

But what I get is:

'Mary has a pet called #<Cat:0x00000002784c20>'

Code Below:

class Person
    def initialize(name)
        @name = name
        @pet = nil
        @hobbies = []
    end

    def describe()
        puts "This persons name is #{@name}."
        puts "#{@name}'s hobbies are:"

        @hobbies.map { |hobby| puts hobby }

        if @pet == nil
            puts "#{@name} has not got any pets."
        else
            puts "#{@name} has a pet called #{@pet}"
        end
    end

    attr_accessor :pet, :hobbies
end
class Cat < Animal

def initialize(name)
    @name = name
end
end


satan = Cat.new("Satan")
mary = Person.new("Mary")
mary.pet = satan

mary.describe

Thanks for all your help.

5
  • Please share your Cat class as well. Commented Jul 1, 2017 at 13:55
  • Are you getting Mary has a pet called #<Cat:0xsome_hex>? Commented Jul 1, 2017 at 14:03
  • How is this question related to Ruby on Rails? Commented Jul 1, 2017 at 14:07
  • @SujanAdiga yup this is exactly what I'm getting. Commented Jul 1, 2017 at 15:12
  • @FreddieCodes then try "#{@name} has a pet called #{@pet.name}" Commented Jul 1, 2017 at 15:28

1 Answer 1

2

In your describe() function, you are calling the object Cat without specifing the name.

But if you call #{pet.name} it will throw:

<undefined method `name' for #<Cat:0x0055d750a1a450 @name="Satan">

You have to allow the access to the variable name in the Cat class first with attr_accessor

class Cat < Animal
  attr_accessor :name # First allow access

end


class Person
  def describe()
     puts "#{@name} has a pet called #{@pet.name}" # Then call the pet's name!
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, this worked a treat and now I understand better how and when to use attr_accessor .
Glad it helps you out! Check out for @Gerry solution to see attr_reader, it is not a bad idea. Either way, try to read documentation about them both. Please do not forget to tick this answer if it solved your problem.
Your answer is better, nicely explained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.