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
但是,如果我只是首先在该方法中声明该变量,它会起作用吗?因为它设置为gets.chomp。我之前通过使用$符号尝试过,它似乎没有工作 – JoshRicha 2014-09-06 15:02:33
我更新了我的答案以使事情更清楚,但如果问题仍然存在,请随时提问。如果您发现它有用,请考虑通过点击答案旁边的复选标记来接受它。 – kriskova 2014-09-06 15:48:40