How can i use a global variable in ruby? [closed]

How can i use a global variable in my function? this is my whole script, i dont want to use class, only i would like to use my variable h in my func1

h = {foo: 1, bar: 2, baz: 3}
total = h.values.sum

def func1 ()
    h.each do |key, value|
        puts "#{key}"
    end
    
    puts h.keys.count
end


func1()

i am getting this error:

`func1': undefined local variable or method `h' for main:Object (NameError)

what is the wrong?


Solution 1:

When you want to use your local variable (it is not a global variable) in your method then you have to pass it to your questions, for example, like this:

h = { foo: 1, bar: 2, baz: 3 }

def func1(hash)
  hash.each do |key, value|
    puts "#{key}"
  end
    
  puts hash.keys.count
end

func1(h)
#=> foo
    bar
    baz
    3

Solution 2:

As noted in @spickermann's answer, passing local variables to methods is the best way to do things, but if you actually want to create a global (use extreme discretion), you use a $ on the variable name.

$h = {foo: 1, bar: 2, baz: 3}

def func1
    $h.each do |key, value|
        puts "#{key}"
    end
    
    puts $h.keys.count
end

func1