From: dblack@... Date: 2006-08-07T05:48:56+09:00 Subject: Re: Method behaviour Hi -- On Mon, 7 Aug 2006, Sard Aukary wrote: > Some methods like > > def change(word) > word[0]='e' > end > a="affluent" > puts a > change(a) > puts a > > alter the original object outside of the method, where as others don't. > > def change(word) > word="fish" > end > a="cow" > puts a > change(a) > puts a > > > Why the change in behaviour, what determines it? Is the only way I can > write methods that change the original object by using the Ruby methods > that do this? It's because there's a distinction between (a) sending a message to an object, and (b) assigning to a variable. a = "cow" # assignment a[0] = 'w' # send message "[]" to a a = "fish" # assignment -- reusing the identifier 'a' Whenever you assign to a variable, you're wiping the slate clean: the variable loses all association with the object it referred to previously (if any). The "word[0] = 'e'" expression looks like assignment, but technically it's calling the method "[]=" on the object word, with the single argument 'e'. It's not the same as just plain assignment to an identifier. David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy ----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <----- http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log http://www.manning.com/black => book, Ruby for Rails http://www.rubycentral.org => Ruby Central, Inc.