【问题标题】:How to treat an object I created using a class like an array如何处理我使用像数组这样的类创建的对象
【发布时间】:2015-06-18 01:00:18
【问题描述】:

所以我将一个散列作为单个参数传递给这个类,然后返回一个嵌套数组。我将哈希转换为数组没有问题,但是,我不知道如何让下面的测试代码工作。我需要像访问数组一样访问对象,同时还要调用对象的实例方法。提前谢谢你们,任何帮助将不胜感激。

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

【问题讨论】:

    标签: ruby arrays object instance-methods


    【解决方案1】:

    你正在覆盖你的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2019-04-09
      相关资源
      最近更新 更多