Ruby中的类继承

Ruby中的类继承,ruby,Ruby,为什么要将数字作为数组返回 class Employee def initialize(n,i,ph,ad) @number = n, @id = i , @phone = ph, @adress =ad end end class Getemploy < Employee def get_data return "The employee number is : #{@number} with id : #{@id} with phone #{@phone}

为什么要将数字作为数组返回

class Employee
  def initialize(n,i,ph,ad)
    @number = n, @id = i , @phone = ph, @adress =ad
  end
end
class Getemploy < Employee
  def get_data
    return "The employee number is : #{@number} with id : #{@id} with phone #{@phone} with adress: #{@adress}"
  end
end

puts Getemploy.new("1","2","3","4").get_data
# => The employee number is : ["1", "2", "3", "4"] with id : 2 with phone 3 with adress: 4
class员工
def初始化(n、i、ph、ad)
@号码=n、@id=i、@phone=ph、@address=ad
结束
结束
类Getemploy员工编号为:[“1”、“2”、“3”、“4”],id:2,电话3,地址:4

行为是由赋值表达式引入的,而不是由继承引入的。键入时:

@number = n, @id = i , @phone = ph, @adress =ad
真正的意思是

  • ad
    分配给
    @地址
  • ph
    分配给
    @phone
  • i
    分配给
    @id
  • 分配[
    n
    ,将
    i
    分配给
    id
    的结果,即
    i
    ,将
    ph
    分配给
    phone
    的结果,即
    ph
    ,将
    ad
    分配给
    address
    的结果,即
    ad
    ]分配给
    number
    ,即列表
因此,要解决该问题,您需要单独指定属性,如下所示

@number = n
@id = i 
@phone = ph
@adress = ad
编辑:你也可以很聪明,做一件事,就像这样

@number , @id , @phone , @adress = [n, i, ph, ad]
为什么要将数字作为数组返回

class Employee
  def initialize(n,i,ph,ad)
    @number = n, @id = i , @phone = ph, @adress =ad
  end
end
class Getemploy < Employee
  def get_data
    return "The employee number is : #{@number} with id : #{@id} with phone #{@phone} with adress: #{@adress}"
  end
end

puts Getemploy.new("1","2","3","4").get_data
# => The employee number is : ["1", "2", "3", "4"] with id : 2 with phone 3 with adress: 4
您可以在
Employee#initialize
方法中将多个值分配给
@number
。Ruby表示多个值的方式为
数组

IOW:


谢谢帮了大忙