2012-03-18 45 views
-2

我写下一个示例程序,我不明白的构造函数如下:红宝石 - 调用不带参数及去除换行符

  1. 为什么不带任何参数的构造函数不是在Ruby的叫什么?
  2. 我们如何在类的定义之外访问类变量?
  3. 为什么它总是在字符串的末尾追加换行符?我们如何剥离它?

代码:

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 
+1

您正在使用“puts”,后者附加换行符。 – 2012-03-18 17:59:04

+0

在回答#2中,您可能想要将getCount定义为类方法,而不是实例方法。然后你会调用Employee.getCount,而不是在实例上调用getCount。 – 2012-03-18 18:04:51

+0

是的,这是可以做到的,但我试图访问Employee。@@ employeeCount用于抛出错误。这是访问静态变量的错误方式吗? – 2012-03-18 18:09:34

回答

1

的换行是来自用户的输入。当用户键入内容并用换行符结束输入时(输入键),换行符被视为输入的一部分。你可以用String#strip()方法剥离其关闭:

empName = empName.strip 

或使用就地方法:

empName.strip! 

要检索你需要一个静态的吸气剂类变量的值(注意self.) :

def self.getCount 
    return @@employeeCount 
end 

或者,你可以通过class_variable_get方法。

+0

地带作品,关于我的第二个问题的任何建议? – 2012-03-18 18:14:43

+0

我已经更新了答案。 – 2012-03-18 18:16:32

+0

看起来'class_variable_get'是一个私有方法,Ruby不响应它。但是,是的,静态方法是一种选择,但我仍然对如何直接访问类变量感到好奇。 – 2012-03-18 18:18:37

0

对于问题1:为什么在Ruby中不调用没有任何参数的构造函数?

您写了def initiaze()。正确的是def initialize()

def initialize() 
    @@employeeCount += 1 
    puts ("Initialize called!") 
end 
0
  1. 你似乎已经注意到你拼错initialize时 定义方法
  2. 不能引用类变量在类的外部直接 ,但你可以做类或使用实例访问器,或使用 Module#class_variable_getEmployee.class_variable_get(:@@employeeCount)
  3. gets返回用户输入的全行,包括终止换行符。另一个建议String#strip的建议,但这将删除所有尾随和领先的空白。如果你只是想删除换行符,使用String#chompempName = empName.chomp!要小心,如果你很想直接适用于格格作为获取得到将在文件末尾返回nil,你会提高NoMethodError发送:格格为零

顺便说一下,你的camelCasedNames不是很好的ruby风格。常量应该全部为UPPER_CASE,除了类名和模块名称(应该使用前导上限),所有其他名称应该是lower_case_with_underscores_to_separate_words。另外,在ruby中,通常会在无争议的方法调用和定义中省略空的parens。