0

There is a question where @coreyward talks about using it alone, but doesn't give an example of when. Other sources on the web allude to some use cases, but I have yet to find any source that lists a real world example. When would you want to write data but not be able to read it?

sawa
  • 165,429
  • 45
  • 277
  • 381
pieguy
  • 95
  • 2
  • 10
  • 2
    This may be a question that is of interest to some readers but I don't think it's suitable for SO. SO questions are intended to fix broken code or to suggest how something could be done in code. In fact, this question has little to do with Ruby. It's more about situations where an object within an instance of a class can be altered but not read from outside the instance, regardless of the object-oriented language. As to the question: in an auction app one might have an instance variable `@last_bid` that bidders could change but not read. Thatj would seem to be a poor design, however. – Cary Swoveland Jan 28 '18 at 19:23

1 Answers1

4

It isn't always, necessarily, that you don't want to read it; sometimes the default writer is fine, but you want a custom reader. Take, for instance, this person class:

class Person
  attr_writer :name
  attr_accessor :title

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

  def name
    "#{@title} #{@name}"
  end
end

Here, creating a reader through attr_reader or attr_accessor for name would be redundant, since I'm defining my own name method because there is a custom rule, that I should always display the name with a title.


As an aside, one could argue that my name method should be something more along the lines of name_with_title or what have you, but I still wouldn't actually want the default name method from a reader, because I still want all access to the name to go through this other method.

Simple Lime
  • 10,790
  • 2
  • 17
  • 32
  • Not only redundant but with warnings turned on you'll get an alert because you've stomped the previous `name` method. – tadman Jan 28 '18 at 19:24
  • 3
    I think a much more common case would be a public `attr_reader` and a private `attr_writer` in the same class. – moveson Jan 28 '18 at 20:08