Ruby - calling constructor without arguments & removal of new line characters
Posted
by
Raj
on Stack Overflow
See other posts from Stack Overflow
or by Raj
Published on 2012-03-18T17:51:57Z
Indexed on
2012/03/18
17:54 UTC
Read the original article
Hit count: 287
ruby
|constructor
I am a newbie at Ruby, I have written down a sample program. I dont understand the following:
- Why constructor without any arguments are not called in Ruby?
- How do we access the class variable outside the class' definition?
- Why does it always append newline characters at the end of the string? How do we strip it?
Code:
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}")
Output:
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
Thanks
© Stack Overflow or respective owner