attr_reader creates these accessor methods for you. : attr_reader « Class « Ruby






attr_reader creates these accessor methods for you.



class Song 
    def initialize(name, artist, duration) 
        @name = name 
        @artist = artist 
        @duration = duration 
    end 
    def name 
        @name 
    end 
    def artist 
        @artist 
    end 
    def duration 
        @duration 
    end 
end 
song = Song.new("A", "B", 2) 
puts song.artist 
puts song.name   
puts song.duration

class Song 
    def initialize(name, artist, duration) 
        @name = name 
        @artist = artist 
        @duration = duration 
    end 
    attr_reader :name, :artist, :duration 
end 

song = Song.new("A", "B", 6) 
puts song.artist 
puts song.name  
puts song.duration 

 








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.Use attr_reader to add a new attribute and use initialize method to set it