Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list local-variables in Ruby?

def method   a = 3   b = 4    some_method_that_gives # [a, b]  end 
like image 769
Cheng Avatar asked Dec 20 '10 06:12

Cheng


People also ask

How do you define a local variable in Ruby?

Local Variables: A local variable name always starts with a lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method.

How do you read a variable in Ruby?

Here is an example showing the usage of global variable. NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.

What is $_ in Ruby?

$_ is the last string read from IO by one of Kernel. gets , Kernel. readline or siblings. Pry introduces the underscore variable, returning the result of the last operation, on its own. It has nothing to do with ruby globals.

How do you declare a global variable in Ruby?

Dissecting Ruby on Rails 5 - Become a Professional DeveloperGlobal variables are always prefixed with a dollar sign. It is necessary to define a global variable to have a variable that is available across classes. When a global variable is uninitialized, it has no value by default and its use is nil.


2 Answers

local_variables

It outputs array of symbols, presenting variables. In your case: [:a, :b]

like image 54
Nakilon Avatar answered Sep 20 '22 05:09

Nakilon


local_variables lists local variables but it lists them before they are defined. See this:

p local_variables a = 1 p local_variables 

this outputs

[:a] [:a] 

which may not be what you expect. Contrast with defined?

p defined? a a = 1 p defined? a 

which outputs the more anticipated

nil "local-variable" 
like image 42
starfry Avatar answered Sep 21 '22 05:09

starfry