Search code examples
functioncrystal-lang

How to access global variables inside functions


I have following simple code:

line = "Hello"

def myfn()
    puts line
end

myfn()

The variable line is not accessible in function. How can global variables be accessed inside functions?


Solution

  • You could make it a constant via capitalization.

    LINE = "Hello"
    
    def myfn()
        puts LINE
    end
    
    myfn()
    

    If you want it to be variable pass it in as an argument, that's what they're for.

    line = "Hello"
    
    def myfn(msg)
        puts msg
    end
    
    myfn(line)