Problems with Methods


#1



Why doesn't my code work?
when i run it, i get this error
:2:in count': undefined method+' for nil:NilClass (NoMethodError)
from :5:in <top (required)>'
from -e:1:in
load'
from -e:1:in `'

I haven't been doing ruby for quite a while but i thought that everything was correct. Doesn't a method just run a block of code?

def count
  counter += 1
end
counter = 0
count
counter += 1
puts counter


#2

The above illustrates scope differences between a local variable and a global variable.

Inside the method, counter is a local variable

Outside of the method, counter is a global, which unlike in JavaScript, cannot be seen inside the method.

Consder the following:

def count
  $counter += 1
end

$counter = 0
count
puts $counter
puts count

Output

 1
 2
=> nil

The prefix, $ denotes a variable as global that is universally available to all methods and objects. You will read that globals have their down side, so be sure to follow up on this concept.

To further illustrate,

$counter = 0
10.times { puts count }
Output

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
=> 10

#3

oh okay, I'm not crazy, they just didnt teach me that yet.
so if i plan on using variables both inside and out of methods, put a $ in front of it
I have to reach that section and learn more about it. thank you!


#4

Until the concept is covered, try to avoid using globals. You shouldn't need to in any of the lessons, as far as I remember.