0

I am quite new to both Stack Overflow and Ruby so I apologize in advance if I have not formatted something correctly but I would love some assistance on calling or displaying the value of arrays from a parent class through an object.

The following code is a task / study drill I am doing as part of the book Learn Ruby the Hard Way (exercise 42):

## Person is-a object
class Person

    def initialize(name)
        ## class Person has-a name
        @name = name

        ## person has-a pet of some kind
        @pet = nil
    end

    @possessions = ['house', 'car', 'clothes', 'furniture', 'guitar']

    attr_accessor :pet
    attr_accessor :possessions
end

## class Employee is-a Person
class Employee < Person

    def initialize(name, salary)
        ## set the @name attribute from class Person
        super(name)
        ## class Employee has-a salary
        @salary = salary
    end


    tasks = {"emails" => "Must answer all emails right away", 
            "reports" => "File two reports once a month",
            "reimbursement" => "File expenses to get reimbursements"
    }

    attr_accessor :tasks 
end

## Mary is-a person
mary = Person.new("Mary")

## Frank is-a Employee
frank = Employee.new("Frank", 120000)

# Study drill 4
puts mary.possessions[4]
puts frank.tasks["emails"]

The following is what my terminal returns when I run the script (basically an empty space):

Macintosh:mystuff3 Vallish$ ruby ex42d.rb

Macintosh:mystuff3 Vallish$ 

I think that I have the wrong syntax or I am creating my arrays/hashes incorrectly and I would love some assistance with this.

My objective is to basically try to pass a values from an array and a hash in a class to it's related objects and then call those values.

Thanks in advance!

1 Answers1

0

You're setting the value of @possessions and @tasks in the wrong place. They should be set inside an instance method (whether initialize or something else), not in the class body itself.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • Thanks so much! This worked wonderfully for the issue with calling arrays. Is there a particular syntax/workflow to call hashes? I tried setting the hash inside an initialize method but I am getting the following error: `ex42d.rb:99:in \`
    ': undefined method \`tasks' for # (NoMethodError)`
    – Karthik Soravanahalli Sep 21 '15 at 00:32
  • Can you send me your current code in a gist? I did the fixes I mentioned and it worked for me. (Note, `@tasks = {...}` or `self.tasks = {...}`, not just `tasks = {...}`.) – C. K. Young Sep 21 '15 at 00:40
  • My apologies! I had forgotten the '@' symbol in front of my tasks hash. After adding it everything is working great, thanks so much! – Karthik Soravanahalli Sep 21 '15 at 00:57