Equal sign in Ruby method definition

Asked

Viewed 160 times

11

I have come across the following definitions of methods and I would like to know the difference between the first definition and the second.

This first has no equal sign in the definition:

def nome
    nome_exibicao(:nome)   
end

Already 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

2 answers

3

Accessors and modifiers methods are very common and give the idea of properties. There is a convention for defining these methods, which most Ruby developers follow (just 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:

  • 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?

2


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
  • Excellent answer. I now understand that this is a normal Setter but in the Ruby way of writing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.