Getter and setters

Well ever heard of the words absraction, why is it important?, honestly i hate buzz words but they are here,when you call a method like "JANE".downcase.We don't really care much about how string get downcased we only know it will be downcased.The details are hidden this data hiding is what called abstraction.Let's say we want to create a class that allow us to instantiate object and later able to

Setter

This is a method used to set value of variable in a created object

1
2
3
4
5
6
class BankTransaction
...
    def bank_name=(bank_name)
      @bank_name = bank_name
    end
end

Note the use of = that is bank_name= ,this is special syntax for the setter methods

Getter

This method is used to read value of variable in object created, this

1
2
3
4
5
6
7
class BankTransaction 
 ....
 ....
    def bank_name
      @bank_name 
    end
end
1
2
3
4
5
6
7
class BankTransaction
    def initialize(your_busines)
     @your_busines
    end
    ...
    ...
end
  • create a class, Movie with initialize method, setter methods and getter methods, name
  • create an object safe_mumbai using class(Movie) you create, during instantation of the object give the name "olympus has fallen", try reading the name of
  • create an object classic_naija, set the name as "rise of the titan", try reading the name
  • change the name of classic_naija to "the fall of titan", try reading it.

Attritube readers, writers and accessors

Write method to read and write values can be cumbersome at times that the good thing about ruby creator new you are lazy and came up with even shorter approach.

Attribute writer(attr_writer)

Attribute writer is used in place of setter method, the keyword is attr_writer

Now let us tweak our code to set the name of bank using attr_writer like so:

1
2
3
4
5
class BankTransaction
...
...
attr_writer :bank_name
end

Delete the setter method and run the code, note the bank_name starts with a colon(:bank_name).that is a symbol.Symbols are a kind of naming or labeling facility. They’re a cousin of strings, although not quite the same thing

Attribute reader(attr_reader)

Attribute reader is used in place of getter method, the keyword is attr_reader

Now let us tweak our code to set the name of bank using attr_reader like so:

1
2
3
4
5
class BankTransaction
...
...
attr_reader :bank_name
end

Delete the getter method and run the code,just like attr_writer the bank_name is a symbol

Atrribute accessor(attr_accessor)

This combines both writer and reader methods it mostly used since most of the time you to both read and write values

1
2
3
4
5
6
7
8
class BankTransaction
...
...
attr_accessor :bank_name
end
bank1 = BankTransaction.new
bank1.name=("Equity")
puts bank1.name()

You can now delete both our attr_reader and attr_writer and run the code

1
$ruby bank_transaction.rb