obj.method(参数)

时间:2016-04-08 15:07:34

标签: ruby object methods

我正在看这段代码:

class Student 
  attr_accessor :first_name, :last_name, :age
  def initialize(first, last, age)
    @first_name = first
    @last_name = last
    @age = age
  end

  def birthday
    @age += 1
  end
end

class ViewStudent
  def initialize(student)
    @student = student
  end

  def do_something
    puts "Student name: #{@student.first_name} #{@student.last_name}"
  end
end

class UpdateStudent
  def initialize(student)
    @student = student
  end

  def do_something
    puts "What is the student's first name?"
    @student.first_name = gets.chomp
    puts "What is the student's last name?"
    @student.last_name = gets.chomp
    puts "Updated student: #{@student.first_name} #{@student.last_name}"
  end
end

choices = [ViewStudent, UpdateStudent]

student = Student.new("John", "Doe", 18)

puts "Select 1 to view student or 2 to update student."
selection = gets.chomp.to_i
obj = choices[selection - 1]
obj = obj.new(student)
obj.do_something

在最后五行中,我了解selection = gets.chomp.to_i将选择选项转换为整数,但这与obj = choices[selection - 1]如何协同工作?

我也不确定obj = obj.new(student)obj.do_something做了什么。看起来像一个局部变量被设置为创建一个以student为参数的新对象。但是,obj不是要调用的类或方法吗?

我还可以收集obj.do_something调用为ViewStudentUpdateStudent定义的方法。

我看到this,但它没有回答我的问题。

1 个答案:

答案 0 :(得分:0)

obj = choices[selection - 1]只需选择ViewStudent如果1和UpdateStudent,如果您的数组是2,则按索引(选项[0]或选项[1])。

然后,您在此实例上创建所选类(ViewStudent.newUpdateStudent.new)的实例并调用do_something方法,因为这两种类中的方法都有所不同:

obj = choices[selection - 1] # obj is ViewStudent or UpdateStudent class
obj = obj.new(student) # obj is ViewStudent or UpdateStudent instance
obj.do_something # call `do something` method on instance