如何处理我使用像数组这样的类创建的对象

时间:2015-04-12 18:37:26

标签: ruby arrays object instance-methods

所以我将哈希作为单个参数传入此类,然后返回一个嵌套数组。我将哈希转换为数组没有问题,但是,我无法弄清楚如何让下面的测试代码工作。我需要完全像数组一样访问对象,同时还要调用对象上的实例方法。提前谢谢你们,非常感谢任何帮助。

class Student

    attr_accessor :scores, :first_name

    def initialize(student_data)
       @student_data = student_data
       @first_name = student_data[:first_name]
       @scores = student_data[:scores]
       return @students = @student_data.to_a
    end

    def first_name
    end

    def scores
    end
end

p students[0].first_name == "Alex"
p students[0].scores.length == 5

1 个答案:

答案 0 :(得分:0)

你在内部没有任何东西覆盖你的getter方法。

您正在替换:

def first_name
  return first_name
end

使用:

def first_name
end

我也假设你正确宣布你的学生阵列。类似于:

students = []
students.push(Student.new({first_name: "Alex", scores: [89, 100, 93, 72, 95] }))

然后尝试:

p students[0].first_name == "Alex"
p students[0].scores.length == 5