0
Indexing variable names
let say I am creating 10 points: point = [n, n, n] for n in 1..10 I want to assign them to variables with the same index.. point_n so point_5 = [5, 5, 5]. Is there a way to put that index into the name of variable.?
4 Antworten
+ 2
I believe you can but that's the wrong way to do things! Usually when you ask that question you are really looking for an array.
If you have
points = [
[0,0,0],
[1,1,1],
[2,2,2],
...
]
then `points[0]` gives you `[0,0,0]`, which reads almost like what you said.
+ 1
There are the `instance_variable_set` and `instance_variable_get` functions, also `eval`. Do define a method from a string, there is `define_method`.
Nothing wrong with experimenting of course, but know that if you create N variables in a loop with instance_variable_set, and N is user input for example, you can't really use them in code. (Is string_100 there or not? You don't know while writing your code.)
That means you will likely use instance_variable_get in a loop to use all your variables, and you've just programmed a bad array.
Those functions I listed are mostly for metaprogramming, for example if you have a class that creates classes you will need them. `define_method` is probably the most common.
0
still would like to know if there is a way of creating variable ( possibly methods) names as a result of some operation.. like string1 + string2
0
thanks.. for now array will do