1

I was wondering whether it is possible to create a global variable from within a method.

So in the example below I would like to re-use the s_name variable from outside the method. How can I do this?

# 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

1 Answer 1

4

You can create a global variable from everywhere if you prefix it with a "$" sign, like: $var

If you declare it in a method, make sure you run that method before calling your variable.

For example:

def global_test
    $name = "Josh"
end

$name # => nil

global_test() # Your method should run at least once to initialize the variable

$name # => "Josh"

So, in your example, if you would like to use s_name from outside of your method, you can do it by adding a '$' sign before it like this: $s_name

Here is a good description about ruby variable types:

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

But as you can read in it (and mostly everywhere in "ruby best practices" and styleguides) it is better to avoid global variables.

Sign up to request clarification or add additional context in comments.

2 Comments

But does it work if I only declare the variable within the method first? As it is set to gets.chomp. I tried this before by using the $ sign and it didn't seem to work
I updated my answer to make things more clear, but feel free to ask, if it's still not. If you found it useful, please consider accepting it by clicking on the check mark beside the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.