我写下一个示例程序,我不明白的构造函数如下:红宝石 - 调用不带参数及去除换行符
- 为什么不带任何参数的构造函数不是在Ruby的叫什么?
- 我们如何在类的定义之外访问类变量?
- 为什么它总是在字符串的末尾追加换行符?我们如何剥离它?
代码:
class Employee
attr_reader :empid
attr_writer :empid
attr_writer :name
def name
return @name.upcase
end
attr_accessor :salary
@@employeeCount = 0
def initiaze()
@@employeeCount += 1
puts ("Initialize called!")
end
def getCount
return @@employeeCount
end
end
anEmp = Employee.new
print ("Enter new employee name: ")
anEmp.name = gets()
print ("Enter #{anEmp.name}'s employee ID: ")
anEmp.empid = gets()
print ("Enter salary for #{anEmp.name}: ")
anEmp.salary = gets()
theEmpName = anEmp.name.split.join("\n")
theEmpID = anEmp.empid.split.join("\n")
theEmpSalary = anEmp.salary.split.join("\n")
anEmp = Employee.new()
anEmp = Employee.new()
theCount = anEmp.getCount
puts ("New employee #{theEmpName} with employee ID #{theEmpID} has been enrolled, welcome to hell! You have been paid as low as $ #{theEmpSalary}")
puts ("Total number of employees created = #{theCount}")
输出:
Enter new employee name: Lionel Messi
Enter LIONEL MESSI
's employee ID: 10
Enter salary for LIONEL MESSI
: 10000000
New employee LIONEL
MESSI with employee ID 10 has been enrolled, welcome to hell! You have been paid as low as $ 10000000
Total number of employees created = 0
您正在使用“puts”,后者附加换行符。 – 2012-03-18 17:59:04
在回答#2中,您可能想要将getCount定义为类方法,而不是实例方法。然后你会调用Employee.getCount,而不是在实例上调用getCount。 – 2012-03-18 18:04:51
是的,这是可以做到的,但我试图访问Employee。@@ employeeCount用于抛出错误。这是访问静态变量的错误方式吗? – 2012-03-18 18:09:34