我想要这个:
class Employees
def initialize
attr_accessor :first_name, :last_name, :class
end
person = Hash.new()
person["Lauree Brown"] = "Terminated"
person["Christie Gregour"] = "Active Employee"
person["Ryan Dunn"] = "Active Employee"
返回具有员工身份的员工姓名。我只是打电话给哈希,还是我必须专门打电话给员工?这是完整的代码:
class Employees
def initialize
attr_accessor :first_name, :last_name, :class
end
person = Hash.new()
person["Lauree Brown"] = "Terminated"
person["Christie Gregour"] = "Active Employee"
person["Ryan Dunn"] = "Active Employee"
if person = "Terminated"
puts "#{} is a terminated employee."
else
puts "#{} is an active employee."
end
end
截至目前,它将返回:
is terminated employee.
=> nil
答案 0 :(得分:2)
这是尝试修复它并使其更像Ruby:
class Employee
attr_accessor :first_name, :last_name, :status
def initialize(first_name, last_name, status)
@first_name = first_name
@last_name = last_name
@status = status
end
def to_s
"%s %s is an %s Employee" % [
first_name,
last_name,
status
]
end
end
people = [ ]
people << Employee.new('Lauree', 'Brown', 'Terminated')
people << Employee.new('Christie', 'Gregour', 'Active')
people << Employee.new('Ryan', 'Dunn', 'Active')
people.each do |person|
puts person.to_s
end
目前还不清楚为什么你宣布一个哈希,或者为什么你在attr_accessor
内使用initialize
,这是一个它甚至无法工作的地方,它不是一个实例方法。
还值得注意的是要特别注意=
含义赋值和==
含义比较。在您分配的示例中,因此第一个条件将始终触发,并且还会覆盖任何先前的数据。这可能不是你的意图。
答案 1 :(得分:2)
您可以使用此代码。
person = Hash.new()
person["Lauree Brown"] = "Terminated"
person["Christie Gregour"] = "Active Employee"
person["Ryan Dunn"] = "Active Employee"
person.each do |key, value|
if value == "Terminated"
puts "#{key} is a terminated employee."
else
puts "#{key} is an active employee."
end
end