In summary, getter and Setter methods expose class fields. They can expose the field in a raw way, such as
[privado] meu_campo = 25
[público] get_meu_campo # retorna 25
[público] set_meu_campo(valor) # seta meu_campo para valor (parâmetro)
or may use some kind of logic, such as
[privado] meu_campo = 25
[público] get_meu_campo # retorna 25 * 2
[público] set_meu_campo(valor) # seta meu_campo para valor/2 (parâmetro)
If you still don’t understand what getters and setters are not
reply now. Understand what they are by the links below and continue reading.
In most languages, the naming standard for writing a getter and a Setter is
private int propriedade;
public int getPropriedade() { ... }
public void setPropriedade(valor) { ... }
But in Ruby it’s different
@propriedade = 0
def propriedade; end
def propriedade=; end
Behold a slightly more contextualized application:
class Pessoa < ActiveRecord::Base
attr_accessible :nome, :sobrenome
def nome_completo # getter
"#{@nome} #{@sobrenome}"
end
def nome_completo=(value) # setter
@nome, @sobrenome = value.split(' ')
end
end
If you don’t need any specific logic on the getter or Setter, use the attr_accessor
. That is to say:
class Carro
def velocidade # getter
@velocidade
end
def velocidade=(nova_velocidade) # setter
@velocidade = nova_velocidade
end
end
is the same thing as
class Carro
attr_accessor :velocidade # getter e setter
end
Know that attr_accessor
is a shortcut to
class Carro
attr_reader :velocidade # getter
attr_writer :velocidade # setter
end
Thanks for the reply. But I haven’t quite figured out what makes the sign of = there. Even reading the link. I could explain in a little more detail?
– Wilker