【问题标题】:Ruby - create a global variable from within a methodRuby - 从方法中创建一个全局变量
【发布时间】:2014-10-31 07:19:42
【问题描述】:

我想知道是否可以从方法中创建全局变量。

所以在下面的示例中,我想从方法外部重新使用 s_name 变量。我该怎么做?

# start method
def start

    # Start the story
    puts "Hello and welcome to the superhero space station, my name is Zakhtar and I am a beautiful mermaid."
    puts "Please state your superhero name"

    # Gets superhero name
    print "> "

    # The dollar sign should give the vaiable global scope. Check!
    s_name = gets.chomp

    # Says hello to the superhero
    puts "Pleased to meet you #{s_name}, we are in urgent need of your help!"

    # Line break
    puts "\n"
    puts "Follow me and I will show you the problem..."

    death

# end start method
end

【问题讨论】:

    标签: ruby variables methods


    【解决方案1】:

    你可以在任何地方创建一个全局变量,如果你在它前面加上一个“$”符号,比如:$var

    如果您在方法中声明它,请确保在调用变量之前运行该方法。

    例如:

    def global_test
        $name = "Josh"
    end
    
    $name # => nil
    
    global_test() # Your method should run at least once to initialize the variable
    
    $name # => "Josh"
    

    因此,在您的示例中,如果您想在方法之外使用 s_name,可以通过在其前面添加一个“$”符号来实现,如下所示:$s_name

    这里是关于 ruby​​ 变量类型的一个很好的描述:

    http://www.techotopia.com/index.php/Ruby_Variable_Scope

    但正如您在其中所读到的(并且大部分都在“ruby 最佳实践”和样式指南中),最好避免使用全局变量。

    【讨论】:

    • 但是如果我只先在方法中声明变量,它会起作用吗?因为它设置为gets.chomp。我之前尝试过使用 $ 符号,但它似乎不起作用
    • 我更新了我的答案以使事情更清楚,但如果仍然没有,请随时询问。如果您觉得它有用,请考虑通过单击答案旁边的复选标记来接受它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2011-12-27
    • 1970-01-01
    相关资源
    最近更新 更多