我写了一个课程,并试图打印结果。
当我运行此代码时,我没有收到任何错误,但它没有打印任何内容。它看起来像一片空白。
class Employer
attr_accessor :id, :first_name, :last_name, :date_joined, :type_of_employment, :vehicle, :location
def initialize(id, first_name, last_name, date_joined, type_of_employment)
@employee_id = id
@employee_first_name = first_name
@employee_last_name = last_name
@employee_date_joined = date_joined
@employee_type_of_employment = type_of_employment
@vehicle = "Honda"
@location = "Toronto"
end
end
emp1obj = Employer.new(1, "John", "Smith", "January 1, 2012", "Fulltime")
puts emp1obj
emp1obj.vehicle = "Honda"
puts emp1obj.first_name
puts emp1obj.last_name
emp1obj.location= "Toronto"
有人可以帮我找到问题吗?
答案 0 :(得分:4)
你是如何运行这个文件的?它在这里打印以下输出:
Honda
#<Employer:0x00000001779c68>
请注意,这些是单元化的:
puts emp1obj.first_name
puts emp1obj.last_name
您需要使用:
@first_name = first_name
@last_name = last_name
而不是
@employee_first_name = first_name
@employee_last_name = last_name
在你的构造函数中,如果你想初始化它们。
答案 1 :(得分:0)
下面没有输出任何内容,作为 getter 方法的相应实例变量(@first_name
,@last_name
),:first_name
,{ {1}}分别未分配任何值。
:last_name
执行以下操作
puts emp1obj.first_name
puts emp1obj.last_name
根据您的代码@first_name = first_name
@last_name = last_name
,不需要。
答案 2 :(得分:0)
当您开始了解attr_accessor
的作用时,这很重要。这就是它正在做的事情:
class Employer
def id
@employee_id
end
def id=(str)
@employee_id = str
end
def initialize(id)
@employee_id = id
end
end
emp1obj = Employer.new(1)
puts emp1obj.id
如果要使用不同的实例变量名,则需要将它们用作方法而不是用于setter / getter的变量。
这对你有用:
class Employer
attr_accessor :employee_id, :employee_first_name, :employee_last_name, :date_joined, :type_of_employment, :vehicle, :location
def initialize(id, first_name, last_name, date_joined, type_of_employment)
@employee_id = id
@employee_first_name = first_name
@employee_last_name = last_name
@employee_date_joined = date_joined
@employee_type_of_employment = type_of_employment
end
end
emp1obj = Employer.new(1, "John", "Smith", "January 1, 2012", "Fulltime")
puts emp1obj.employee_id
puts emp1obj.employee_first_name
puts emp1obj.employee_last_name