Indexing variable names | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.?

4th Oct 2018, 3:47 AM
Tomasz Drgas
Tomasz Drgas - avatar
4 Answers
+ 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.
4th Oct 2018, 5:38 AM
Schindlabua
Schindlabua - avatar
+ 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.
4th Oct 2018, 1:52 PM
Schindlabua
Schindlabua - avatar
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
4th Oct 2018, 9:32 AM
Tomasz Drgas
Tomasz Drgas - avatar
0
thanks.. for now array will do
4th Oct 2018, 2:37 PM
Tomasz Drgas
Tomasz Drgas - avatar