def method a = 3 b = 4 some_method_that_gives # [a, b] end
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.
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.
$_ 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.
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.
local_variables
It outputs array of symbols, presenting variables. In your case: [:a, :b]
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With