From: Stefano Crocco Date: 2012-06-21T16:51:09+09:00 Subject: Re: New to Ruby - Scope Question On Thursday 21 June 2012 Emeka Patrick wrote > x = 10 > y = 5 > > def square(x) > puts "within the method x is " + x.to_s > puts x*x > end > > > In the above when defining the method, the x that is being referenced in > "x.to_s" and puts x*x is by default the variable x, defined above, with > a value of 10, correct? This then means that even though this variable > isn't defined within the method it can still be called on from outside > the code. However, if the variable was given a value within the method > then it wouldn't be available outside of the method, correct? > > Can someone explain why this is so. I guess I don't NEED to know why, > but I'd like to understand it a bit better if possible. Thanks! > > -- > Posted via http://www.ruby-forum.com/. No, the x being referred to in the "x.to_s" expression is not the one you set to 10 but the one you gave as argument to the square method. When you define a method, you create a new scope. This means that local variables defined outside the method won't be availlable inside the method body. Also, local variables defined inside the method body (including the arguments of the method) won't be availlable outside the method itself. On the other hand, when you define a method which takes some arguments, you implicitly introduce a local variable for each argument in the scope of the method body. When the method is called, this variables will be given the values you pass as arguments to the method call. All this means that your method would work exactly in the same way even if you called the argument with another name (provided, of course, that you change all references to it to use the new name). For example: def square(z) puts "within the method z is " + z.to_s puts z*z end I hope this helps Stefano