0

hi i m new to ruby on rails please let me know is it possible to declare a variable within the function/method

def fun1
  #initialized a global variable 
end  

def fun2
  #access value   
end 

is it possible get value of a variable declared in fun1 function by fun2 function

Thilo
  • 17,565
  • 5
  • 68
  • 84
Anudeep GI
  • 931
  • 3
  • 14
  • 45

2 Answers2

1

To create a truly global variable, use $:

def fun1
  $foo = 'bar'
end  

def fun2
  puts $foo
end 

Here $foo is available outside the class instance once fun1 has been called.

As noted in the first comment, this should be used sparingly:

They are dangerous because they can be written to from anywhere. Overuse of globals can make isolating bugs difficult; it also tends to indicate that the design of a program has not been carefully thought out.

What you're probably asking for is an instance variable, which uses @:

def fun1
  @foo = 'bar'
end  

def fun2
  puts @foo
end 

Here @foo is available anywhere in the current instance of the class, again once it has been declared by calling fun1.

See for example this on the various variable scopes in ruby.

Thilo
  • 17,565
  • 5
  • 68
  • 84
  • 2
    It is important to note that the use of global variables, `$variable_name` are highly discouraged, especially more so among Ruby developers. – Jason Kim Sep 08 '12 at 05:51
0

First of all, it would be better if you could share your actual scenario for what you need to define a global variable from a function. There might be a better, manageable, DRY approach for your solution.

Secondly, apart from the answer from "Thilo", here are few references showing the usage of global variables for rails in different situations. Not just for ruby. You need it for rails right?

Community
  • 1
  • 1
Samiron
  • 5,169
  • 2
  • 28
  • 55