2014-09-06 95 views
0

我想知道是否可以从方法内部创建一个全局变量。Ruby - 从方法内部创建一个全局变量

所以在下面的例子中,我想重新使用方法外部的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 

回答

2

,如果你有一个“$”符号前缀它,就像您可以从任何地方的全局变量:$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

但是当你CA ñ读入它(主要是在“ruby最佳实践”和styleguides中的任何地方),最好避免全局变量。

+0

但是,如果我只是首先在该方法中声明该变量,它会起作用吗?因为它设置为gets.chomp。我之前通过使用$符号尝试过,它似乎没有工作 – JoshRicha 2014-09-06 15:02:33

+0

我更新了我的答案以使事情更清楚,但如果问题仍然存在,请随时提问。如果您发现它有用,请考虑通过点击答案旁边的复选标记来接受它。 – kriskova 2014-09-06 15:48:40