如何让我的类对象返回一个数组而不是<classobject:0x007fc94a0 ...]>?</classobject:0x007fc94a0 ...]>

时间:2014-06-29 19:54:52

标签: ruby arrays class initialization

!!!!我正在清理我的代码并重新思考我的问题。我会在几分钟内重新发布和编辑版本。感谢您的回复!

这是我的代码:

class Student
   attr_accessor :scores, :first_name

  def initialize(first_name, scores)    
    @first_name = first_name
    @scores = scores
  end

  def average
   @scores.inject {|sum, el| sum + el }.to_f / @scores.size
  end

  def letter_grade
    case average
    when (90..100)
    "A"
        when (80..89)
    "B"
    when (70..79)
    "C"
    when (60..69)
    "D"
    when (0..59)
    "F"
    end
  end
end

me        = Student.new("Alex", [100,100,100,0,100])
student_2 = Student.new('Hodor', [2,2,7,0,90])
student_3 = Student.new('Aria', [90,100,87,90,90])
student_4 = Student.new('Tyrion', [95,100,97,100,30])
student_5 = Student.new('Jaela', [100,100,100,100,100])

students = [me, student_2, student_3, student_4, student_5]

p students

以下是我的回复:

[#<Student:0x007f92a91e6070 @first_name="Alex", @scores=[100, 100, 100, 0, 100]>, #<Student:0x007f92a91e5ff8 @first_name="Hodor", @scores=[2, 2, 7, 0, 90]>, #<Student:0x007f92a91e5f80 @first_name="Aria", @scores=[90, 100, 87, 90, 90]>, #<Student:0x007f92a91e5f08 @first_name="Tyrion", @scores=[95, 100, 97, 100, 30]>, #<Student:0x007f92a91e5e90 @first_name="Jaela", @scores=[100, 100, 100, 100, 100]>]

我想要像[[“Alex”,[100,100,100,0,100],[“Hodor”,[2 ..] ..]]

目标是通过这些测试:

p linear_search(students, "Alex") == 0
p linear_search(students, "NOT A STUDENT") == -1

因此,我认为实际上我需要在学生班内进行这项工作。

2 个答案:

答案 0 :(得分:1)

我不确定练习的目的是什么,但要从实际输出到预期输出,你只需要检查你的元素,并从每个元素中构建一个数组(使用map):

students.map { |x| [x.first_name, x.scores] }
# => [["Alex", [100, 100, 100, 0, 100]], ["Hodor", [2, 2, 7, 0, 90]], ["Aria", [90, 100, 87, 90, 90]], ["Tyrion", [95, 100, 97, 100, 30]], ["Jaela", [100, 100, 100, 100, 100]]]

答案 1 :(得分:1)

如果您尝试输出Student的实例,ruby会在Student实例上调用to_s()。如果您的类没有提供to_s()方法,则会调用继承的to_s()方法(在类Object中),它提供您看到的字符串。如果重新定义Object#to_s,则可以证明:

#Your code here

class Object
  def to_s
    'hello from Object#to_s'
  end
end

p students

--output:--
[hello from Object#to_s,
 hello from Object#to_s,
 hello from Object#to_s,
 hello from Object#to_s,
 hello from Object#to_s]

如果覆盖Student内的to_s()方法,那么每次尝试输出Student对象时,ruby都会调用它并使用其返回值:

require 'pp'

class Student

  attr_accessor :scores, :first_name
  ...

  def to_s
    "#{first_name} #{scores.inspect}"
  end

end



students = [
  Student.new("Alex", [100,100,100,0,100]),
  Student.new('Hodor', [2,2,7,0,90]),
  Student.new('Aria', [90,100,87,90,90]),
  Student.new('Tyrion', [95,100,97,100,30]),
  Student.new('Jaela', [100,100,100,100,100]),
]

pp students

--output:--
[Alex [100, 100, 100, 0, 100],
 Hodor [2, 2, 7, 0, 90],
 Aria [90, 100, 87, 90, 90],
 Tyrion [95, 100, 97, 100, 30],
 Jaela [100, 100, 100, 100, 100]]

在代码片段scores.inspect中,inspect {)方法是p使用的方法,即p scores相当于print scores.inspect + "\n"。但你不能写:

"some string #{p.scores}"

因为字符串插值使用p.scores的返回值,而pputs一样,总是返回nil。