如何访问函数内部的全局变量

How to access global variables inside functions

我有以下简单代码:

line = "Hello"

def myfn()
    puts line
end

myfn()

变量 line 在函数中不可访问。如何在函数内部访问全局变量?

您可以通过大写使其成为常量。

LINE = "Hello"

def myfn()
    puts LINE
end

myfn()

如果您希望它是可变的,请将其作为参数传入,这就是它们的用途。

line = "Hello"

def myfn(msg)
    puts msg
end

myfn(line)

你可以create a module with a class variable if you need a 'global' state.

module Foo
  extend self

  @@line = "Hello"

  def myfn
    puts @@line
  end
end

Foo.myfn

还有一个替代方案:

line = "Hello"

myfn = ->() {
  puts line
}

myfn.call