Use attr_reader to add a new attribute and use initialize method to set it : attr_reader « Class « Ruby






Use attr_reader to add a new attribute and use initialize method to set it


class Employee
      attr_reader :name
      def initialize(name)  
            @name = name 
      end
end

employee1 = Employee.new("Aneesha")

puts employee1.name

 








Related examples in the same category

1.attr_reader creates one or more instance variables, with corresponding methods that return (get) the values of each method.
2.Calling the attr_accessor method does the same job as calling both attr_reader and attr_writer together, for one or more instance methods
3.attr_reader creates these accessor methods for you.