Equal sign in Ruby method definition

11

I came across the following method definitions and would like to know the difference between the first and second definitions.

This first one does not have the equal sign in the definition:

def nome
    nome_exibicao(:nome)   
end

This second has the equal sign:

def nome=(novo_nome)
  if !self[:nome_real]
    self[:nome_real] = novo_nome
    gera_nome_exibicao
  else
    if novo_nome.is_a? Hash
      self[:nome] = novo_nome.sort.map { |b| b[1] }.join(' ')
    else
      self[:nome] = novo_nome
    end
  end   
end
    
asked by anonymous 01.11.2017 / 20:47

2 answers

1

In short, the getter and setter methods expose fields in the class. 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 they can 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)
  

Stop, look and listen
  If you still do not understand what getters and setters are not   answer now. Understand what they are for the links below and continue reading.

     

In most languages, the naming pattern 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

See a slightly more contextualized application :

class Pessoa < ActiveRecord::Base
  attr_accessible :nome, :sobrenome

  def nome_completo # getter
    [@nome, @sobrenome].join
  end

  def nome_completo=(value) # setter
    @nome, @sobrenome = value.split(' ')
  end
end

If you do not need any specific logic in the getter or in the setter, use attr_accessor . That is:

class Carro
  def velocidade # getter
    @velocidade
  end

  def velocidade=(nova_velocidade) # setter
    @velocidade = nova_velocidade
  end
end

is the same as

class Carro
  attr_accessor :velocidade # getter e setter
end

Learn that attr_accessor is a shortcut to

class Carro
  attr_reader :velocidade # getter
  attr_writer :velocidade # setter
end
    
09.12.2017 / 21:09
3

Accessor methods and modifiers are very common and give the idea of properties. There is a convention for defining these methods, which most Ruby developers follow (as Java has the convention for getters and setters):

class Pessoa
  def nome # acessor
    @nome
  end

  def nome=(novo_nome)
    @nome = novo_nome
  end
end

Some articles that may be useful to you:

06.11.2017 / 15:25