+ 1

Class variables

I got bored of searching hahaha Can anybody tell me the best or just some way to declare a variable that can be used in any method of the class? I have 4 arrays in a class and 3 methods. I want to be able to use those 4 arrays without having to declare them in each method! Thanks! :D

7th Nov 2016, 11:03 PM
Matias Schiaffino
Matias Schiaffino - avatar
6 Réponses
+ 2
You could just use global scope, putting a $ before your variable name.
7th Nov 2016, 11:09 PM
Pierre Varlez
Pierre Varlez - avatar
+ 2
I believe the example you gave is right, but I'm not a pro in Ruby either.
7th Nov 2016, 11:17 PM
Pierre Varlez
Pierre Varlez - avatar
+ 1
Ok, thanks man! Now I have a starting point to try :) PD: I'm amazed how fast people answer questions here hahaha
7th Nov 2016, 11:20 PM
Matias Schiaffino
Matias Schiaffino - avatar
+ 1
Global vars are a bad practice most times. I recommend you to uset instance variables for the arrays in the initialize method. If your methods are class methods, use class variables instead.
17th Jan 2017, 10:17 AM
Mariano Giagante
Mariano Giagante - avatar
0
you mean something like: def class SomeClass $variable def some_method #use the variable here end def some_other_method #and here too end end ??
7th Nov 2016, 11:14 PM
Matias Schiaffino
Matias Schiaffino - avatar
0
ooh wait, or the global have to be declare before the class? I don't remember very well, I'm new on this, sorry :(
7th Nov 2016, 11:16 PM
Matias Schiaffino
Matias Schiaffino - avatar