Lets take this simple example class NewBook attr_accessor :books def initialize @books =  end def some_method books #( the reader for books works fine and will recall the class value @books, however) books = [4,5,6,7] # ( books will not actually get assigned here unless I do self.books = [4,5,6,7] ) end end Why do you have to use self.books= on writer methods, but you can simply put books on reader method. Very confused. Any help would be great.
on 2007-04-13 04:28
on 2007-04-13 04:56
On Apr 12, 10:28 pm, Aryk Grosz <tennisbum2...@hotmail.com> wrote: > def some_method > put books on reader method. > > Very confused. Any help would be great. > > -- > Posted viahttp://www.ruby-forum.com/. In the case of "books = foo", ruby thinks books is a new locally scoped variable. It's a ruby language "gotcha". To inform ruby that you want to call the "book=" method on your object, you have to explicitly mention the reciever: "self.book = foo" OR, as long as you are in an instance method of that class, you can just access the instance variable directly: "@book = foo"
on 2007-04-13 04:57
On Apr 12, 2007, at 10:28 PM, Aryk Grosz wrote: > Why do you have to use self.books= on writer methods, but you can > simply > put books on reader method. books = [1,2,3,4] list = [5,6,7,8] Which one is a setter method and which one is an assignment to a local variable? You have to use self.books so that the parser can distinguish between a call to the setter method and a local variable assignment. This is a side effect of their being no need to declare local variables nor a sigil for local variables (like @ and $ for instance and global variables). Gary Wright