【问题标题】:How to call arrays from classes/objects in Ruby (learn ruby the hard way exercise 42)如何在 Ruby 中从类/对象中调用数组(学习 Ruby 的艰难练习 42)
【发布时间】:2015-09-21 07:46:41
【问题描述】:

我对 Stack Overflow 和 Ruby 都很陌生,所以如果我没有正确格式化某些内容,我提前道歉,但我希望在通过对象从父类调用或显示数组值方面得到一些帮助。

以下代码是我在《Learn Ruby the Hard Way》(练习 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"]

以下是我运行脚本时终端返回的内容(基本上是空白):

Macintosh:mystuff3 Vallish$ ruby ex42d.rb

Macintosh:mystuff3 Vallish$ 

我认为我的语法有误,或者我创建的数组/哈希不正确,我希望得到一些帮助。

我的目标基本上是尝试将数组中的值和类中的哈希传递给它的相关对象,然后调用这些值。

提前致谢!

【问题讨论】:

    标签: ruby learn-ruby-the-hard-way


    【解决方案1】:

    您将@possessions@tasks 的值设置在错误的位置。它们应该设置在实例方法中(无论是initialize 还是其他),而不是类主体本身。

    【讨论】:

    • 非常感谢!这对于调用数组的问题非常有效。是否有特定的语法/工作流程来调用哈希?我尝试在初始化方法中设置哈希,但出现以下错误:ex42d.rb:99:in `&lt;main&gt;': undefined method `tasks' for #&lt;Employee:0x007fd84b96b9e8&gt; (NoMethodError)
    • 你能把你当前的代码发给我吗?我做了我提到的修复,它对我有用。 (注意,@tasks = {...}self.tasks = {...},而不仅仅是 tasks = {...}。)
    • 抱歉!我忘记了任务哈希前面的“@”符号。添加后一切正常,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 2013-04-06
    • 2011-12-04
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    相关资源
    最近更新 更多