From: Stefano Crocco Date: 2009-08-27T18:18:03+09:00 Subject: Re: A bizarre problem with data= methods On Thursday 27 August 2009, David Espada wrote: > |Hi all. > | > |I have found an error that does not understand. Look this simple code: > | > |--------------------------------- > |class Foo > | def value=(data) > | puts "Look #{data}" > | end > |end > | > |f = Foo.new.value = "at me" # => Look at me > |--------------------------------- > | > |Great! A little assigner that works perfectly. But now I make a > |constructor that use the assigner directly: > | > |--------------------------------- > |class Foo > | def initialize(data) > | value = data > | end > | > | def value=(data) > | puts "Look #{data}" > | end > |end > | > |f = Foo.new("at me") # => Nothing!!!!!!!!! > |--------------------------------- > | > |Why? The constructor doesn't use value= method. What is happening? Is > |that normal? > | > |Thanl you for your help. > | Because when ruby sees something like: identifier = value it thinks you're creating a local variable called identifier, not calling the identifier= method. To force ruby to understand you want to call the method, you need to use the dot notation, self.identifier = value, or use send: send(:identifier=, value). I hope this helps Stefano