Understanding Ruby Setters

Bitwise

If I create a class like this:

class Player

  def initialize(position, name)
    @position = position
    @name = name
  end

end

Isn't that setting the name to an instance variable? if so, why would I need to write a setter like this

 class Player

  def initialize(position, name)
    @position = position
    @name = name
  end

  def name=(name)
    @name = name
  end

 end

Basically when is it necessary to write getters in a class?

Surya

Getters and setters job is to provide you a quick implementation of read and write of instance variables that you define in your constructor:

class Player
  attr_accessor :name, :position
  def initialize(position, name)
    @position = position
    @name = name
  end
end

you can also user attr_reader(for getters) and attr_writer(for setters) specifically for these variables.

Above code: attr_accessor :name, :position gives you: #name, #position, #name=, and #position= methods for instance of Player class.

However, they're not going to give you validation or a customized logic for getters/setters.

For example: you might want to show a player's full name or do not wish your code to accept a 0 or negative position, in such a case you'd have to write getter and setter yourself:

class Player
  def initialize(first_name, last_name, position)
    @first_name = first_name
    @last_name = last_name
    @position = position
  end

  # validation for updating position using setter of position
  def position=(new_position)
    raise "invalid position: #{new_position}" if new_position <= 0
    @position = new_position
  end

  # customized getter for name method
  def name
    "#{@first_name} #{@last_name}"
  end
end

If you do not require customization as stated above then using attr_* method for these variables makes more sense.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related