development

Ruby Class Members: Getter & Setter

The simplest example of read_attr, write_attr in a class.

class Person  
  attr_reader :name, :age   
  attr_writer :name, :age   # creates the setter methods       
    
  def initialize(name)  
    [@name](http://twitter.com/name) = name  
  end  
endmike = Person.new('Mike')   
mike.age = 20               # calling setter method  
mike.age                    # calling getter method, returns 20

Reference

The example is verbatim from an easy to follow tutorial on Ruby class: https://medium.com/@rondwalker22/how-getter-setter-methods-work-in-ruby-c5f5da07f99

Categories: development

Tagged as: , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.