From: "Jan E." Date: 2012-07-01T03:37:28+09:00 Subject: Re: Accessor Methods with a Twist Hi, Doug Jolley wrote in post #1066764: > I guess the problem is that I don't know what receiver to use. > Thoughts? I seems you haven't fully understood the concept of object orientation. It makes no real sense to create instance variables and define methods on the top level. While this does work and may actually be useful in some special cases, the code should rather be in a *class*. For example: class Person def initialize name @name = name end def name @name end def name= new_name @name = new_name end end This creates a class Person with three method definitions in it. When you create a Person object via Person.new, you have to first provide a name. This name will be saved in the @name variable of the object (this is done by the initialize method): person_1 = Person.new 'Doug' You can now call "name" or "name=" on the object in order to get or set the @name variable: puts person_1.name # this outputs "Doug" person_1.name = 'Fred' # change the @name variable of person_1 to "Fred" puts person_1.name # now you get "Fred" Of course, you can do this not only on the top level but also in modules or anywhere else. But you have to create an instance of Person first. Some other things to note: - You don't have to write getters and setters by hand. You can simply call "attr_accessor" within the class body and supply the variable names as Symbols: class Person def initialize name @name = name end attr_accessor :name end This automatically creates a "name" and a "name=" method. - You don't have to use parantheses for method calls. While many people still use them for clarity, it's common to omit them for basic methods like "puts" and getter methods (this makes it look like you were actually accessing the variables of the object rather than calling methods). - I wouldn't use "::" when calling module or class methods. This is allowed, but I'd rather stick with the normal dot and use the double colon only for constants. - When define class methods inside a class body, you should use "self" as the receiver rather than write out the actual class name. This makes the code much more flexible, because renaming the class won't break the whole code. -- Posted via http://www.ruby-forum.com/.