Variables in and out of methods


#1



This is where I started messing around with the code.


I was just messing around with creating methods and seeing if I can link the variables in one method to a completely new method. If I reference method2 within method1 the variable's value holds, but as soon as the method creating the variable ends, the variable's value returns to nil.


*** THIS ONE WORKS FINE ***

def cubertino(n)
  puts n ** 3
end

def teeth_cubed
    puts "Number of teeth?"
    new = gets.chomp.to_i
    if new != 0 
        cubertino(new)
    end
end

teeth_cubed

-----------------------------------------------

*** THIS ONE DOES NOT WORK ***
ph = 0

def teeth(ph)
    puts "Number of teeth?"
    ph = gets.chomp.to_i
end

teeth(ph)
puts ph

Any ideas on holding a variable's value out of the method used to create it? Is this an actual problem? Thanks.


#2

Globals that need to be visible in methods must be declared as global.

$ph

This makes it truly global and visible in all scopes.

Global variables


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.