I’m trying to pass to a method all the parameters in a global variable:
To answer your question:
$allparameters=[“dos”,“ie”,“4”,“alone”,“”,“8”]
and
$allparameters=“dos”,“ie”,“4”,“alone”,“”,“8”
does the same - it assigns the array [“dos”,“ie”,“4”,“alone”,“”,“8”] to
the global variable $allparameters.
After this, you want
myclass.mymethod(*$allparameters)
The problem is that myclass.mymethod expects 6 parameters, whereas you
pass in an array containing 6 things (but that’s still 1 parameter, no
matter how much of what it contains). The splat or unnarray operator (*)
splits it up into 6 pieces which is what your function wants.
I am quite sure that more people will join this thread, so I am leaving
the “never use global variables”, “using 6 unnamed params is probably
not a very good idea”, “allparameters is not the Ruby way to name a
variable” style comments to them
Thanks for your comments.
This is only an example the real name of my global variable is:
$txLoginData
That’s only a bit better :-). The Ruby convention would be to call it
tx_login_data in this case. However, this is really up to you as far as
you are consistent in naming your variables (or you’d like to merge your
code later with somebody using different naming conventions, e.g.
Ruby’s).
What’s worse is the usage of global variables which is not recommended.
I am not sure what are you working on though - maybe you are porting
something over from a different language which is full of global
variables, and you are not going to use this code too much in the
future.
However, if that’s not the case, and mainly if you are writing the code
from scratch, factoring out the global variables would be a good idea in
99.9% of the cases…
I’m using global variables because I have a settings file with all the
global variables and the final user can change the values only in that
file.
I don’t have any practice in Ruby (2 weeks), is there a better way?
I’m using global variables because I have a settings file with all the
global variables and the final user can change the values only in that
file.
As far as I understand the situation (maybe I don’t), this has nothing
to do with the scope of the variables used.
The notion of a ‘settings file’, as used in other languages like Java,
is quite alien to Ruby. In Ruby, the configurations stuff is code, too
(a typical example of this is config/environment.rb in Rails).
I don’t have any practice in Ruby (2 weeks), is there a better way?
Yeah for sure. We would need a more detailed description of the problem
to come up with a solution, though.