Last Updated: February 25, 2016
·
6.235K
· jmarizgit

Ruby: automatic get and set methods

Like in Java, Ruby provide syntax sugar to generate automatic get and set methods.

Without automatic get and set you need to create something like this:

class Phone
    def set_model ( model )
        @model = model
    end
   def get_model
        @model
   end
end

That works fine, but is a lot of work if we need to define multiple methods for get and set. To fix that you can use "attr_accessor", like this:

class Phone
    attr_accessor :model
end

Open your terminal, run irb command (interactive ruby shell), inside irb do the following (I'm assuming you are at the same directory as your .rb file):

> require './Phone'  #! import class
> myphone = Phone.new  #! instantiate class Phone
> myphone.model = "iPhone5"  #! set model name
> myphone.model  #! get model name

Enjoy.

3 Responses
Add your response

Hey, cool tip, just wanted to point something out:
Technically, without attr_accessor, you could still do:

class Phone
def model= ( model )
write_attribute(:model, model)
end
def model
@model
end
end

And use it just as if you would've used attr_accessor:

require './Phone' #! import class
myphone = Phone.new #! instantiate class Phone
myphone.model = "iPhone5" #! set model name
myphone.model #! get model name

over 1 year ago ·

Thanks for point that out @deleteman

over 1 year ago ·

FIY, you could also use attr_reader, ans attr_writter.
Some sorts of Ruby basics.

over 1 year ago ·