DEV Community

pooyaalamdari
pooyaalamdari

Posted on

attr method

class Ticket 
    def initialize(venue, date)
        @venue = venue 
        @date = date
    end

    def price=(amount) # write attr
        @price = amount 
    end

    def venue # read attr
        @venue
    end

    def date # read attr 
        @date
    end

    def price # read attr
        @price 
    end
end

thicket = Ticket.new("Hall Town", "01/01/2023")
thicket.price=(100)

puts thicket.venue
puts thicket.date
puts thicket.price
Enter fullscreen mode Exit fullscreen mode

After

class Ticket 

    attr_reader :venue, :date, :price

    def initialize(venue, date)
        @venue = venue 
        @date = date
    end

    def price=(amount) # write attr
        @price = amount 
    end
end

thicket = Ticket.new("Hall Town", "01/01/2023")
thicket.price=(100)

puts thicket.venue
puts thicket.date
puts thicket.price
Enter fullscreen mode Exit fullscreen mode

attr_writer

class Ticket 

    attr_reader :venue, :date, :price

    attr_writer :price

    def initialize(venue, date)
        @venue = venue 
        @date = date
    end
end

thicket = Ticket.new("Hall Town", "01/01/2023")
thicket.price=(100)

puts thicket.venue
puts thicket.date
puts thicket.price
Enter fullscreen mode Exit fullscreen mode

attr_accessor

class Ticket 

    attr_reader :venue, :date

    attr_accessor :price # price has attr_reader and attr_writer together

    def initialize(venue, date)
        @venue = venue 
        @date = date
    end
end

thicket = Ticket.new("Hall Town", "01/01/2023")
thicket.price=(100)

puts thicket.venue
puts thicket.date
puts thicket.price
Enter fullscreen mode Exit fullscreen mode

Top comments (0)