# Method vs variable assigment

**URL:** <https://www.ruby-forum.com/t/method-vs-variable-assigment/58535>\
**Category:** Ruby\
**Created:** [April 22, 2006, 8:43pm UTC](https://www.ruby-forum.com/t/method-vs-variable-assigment/58535 "2006-04-22T20:43:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gioele](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@gioele](https://www.ruby-forum.com/u/gioele)\
**Post date:** [April 22, 2006, 8:43pm UTC](https://www.ruby-forum.com/t/method-vs-variable-assigment/58535/1 "2006-04-22T20:43:49Z")

</div>

I can’t understand why this script

| #!/usr/bin/ruby  
| class A  
| attr\_accessor :v  
|  
| def test  
| p @v  
| end  
|  
| def mod\_explicit\_setter  
| self.v = “explicit setter”  
| end  
|  
| def mod\_setter  
| v = “setter”  
| end  
|  
| def mod\_direct  
| @v = “direct”  
| end  
| end  
|  
| a = A.new  
| p a.methods - Object.new.methods  
|  
| a.mod\_setter; a.test  
| a.mod\_direct; a.test  
| a.mod\_setter; a.test  
| a.mod\_explicit\_setter; a.test

have this output

| [“mod\_setter”, “mod\_direct”, “v”, “v=”, “mod\_explicit\_setter”, “test”]  
| ./vm.rb:7: warning: instance variable @v not initialized  
| nil \<- correct, v is a local variable  
| “direct” \<- correct  
| “direct” \<- correct? v= is an already seen method  
| “explicit setter” \<- correct

I thought that, once ruby sees a methods, it prefers to call that method  
instead of creating a new local variable.

---

<div class="post-metadata">

**Author:** ![gioele](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@gioele](https://www.ruby-forum.com/u/gioele)\
**Post date:** [April 22, 2006, 8:46pm UTC](https://www.ruby-forum.com/t/method-vs-variable-assigment/58535/2 "2006-04-22T20:46:56Z")

</div>

Hi –

On Sun, 23 Apr 2006, Gioele B. wrote:

> | def mod\_explicit\_setter  
> | end
> 
> | [“mod\_setter”, “mod\_direct”, “v”, “v=”, “mod\_explicit\_setter”, “test”]  
> | ./vm.rb:7: warning: instance variable @v not initialized  
> | nil ← correct, v is a local variable  
> | “direct” ← correct  
> | “direct” ← correct? v= is an already seen method  
> | “explicit setter” ← correct
> 
> I thought that, once ruby sees a methods, it prefers to call that method  
> instead of creating a new local variable.

No; actually whenever it sees this:

var = value

it assumes that var is a local variable. So for methods ending in =  
you get the syntactic sugar on the right (= instead of .=()) but not  
on the left (you have to indicate the receiver explicitly).

David

–  
David A. Black (removed\_email\_address@domain.invalid)  
Ruby Power and Light, LLC ([http://www.rubypowerandlight.com](http://www.rubypowerandlight.com))

“Ruby for Rails” PDF now on sale! [Ruby for Rails](http://www.manning.com/black)  
Paper version coming in early May!
