Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal sign in Ruby method definition [duplicate]

Tags:

ruby

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

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

 def name
   display_name(:name)
 end

This second has the equal sign:

 def name=(new_name)
   if! self[:real_name]
     self[:real_name] = new_name
     gera_name_exhibition
   else
     if new_name.is_a? Hash
       self[:name] = new_name.sort.map {| b | b [1]} .join ('')
     else
       self[:name] = new_name
     end
   end
 end
like image 818
MZaragoza Avatar asked Nov 16 '25 04:11

MZaragoza


1 Answers

The first one is declaring the getter for the :name variable. The second one is declaring a setter for the :name variable. And there is additional behaviour there as well.

Here's an example:

class GSExample
  def name
    @name
  end

  def name=(val)
    @name = val
  end
end

e = GSExample.new
puts e.name
# => nil

e.name = 'dave'
puts e.name
# => dave

Above you can see that @name is an instance variable that is used for as a getter with the method name and as a setter for the method name=. The equals sign is ruby convention for setter (we could easily not do a setter, but that would be bad practice.)

Typically getters & setters (or accessors) are done using attr_reader, attr_writer, or attr_accessor if they're simple. In your code they're not so they've been custom defined. You can read a much more through answer here: https://stackoverflow.com/a/4371458/33226

like image 98
Gavin Miller Avatar answered Nov 18 '25 20:11

Gavin Miller