3

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
MZaragoza
  • 10,108
  • 9
  • 71
  • 116

1 Answers1

1

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

Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
  • what is this "`:name` variable" you speak of? – Sergio Tulentsev Dec 27 '17 at 15:55
  • Well, your methods are using a hash to store variables. That's what `self[:name]` is. And your two methods seem to be accessing the data referenced by the key `:name` (there's so missing information in your question, so I'm making assumptions) – Gavin Miller Dec 27 '17 at 15:59