I want to create a new variable from array elements. This is a very bad code and does not work:
(1..5).each {|x| print "step " + x.to_s + ": "; name_of_variable_+_x = gets.chomp}
but I want to understand the meaning of what I want to do.
I want to create a new variable from array elements. This is a very bad code and does not work:
(1..5).each {|x| print "step " + x.to_s + ": "; name_of_variable_+_x = gets.chomp}
but I want to understand the meaning of what I want to do.
This is the case where you use a variable with an Array
.
vars = []
(1..5).each do |x|
vars[x] = gets.chomp
puts "step #{x}: #{vars[x]}"
end
If you really want to define a variable, then you must use eval
. This is a terrible idea because you will be using a very dangerous feature (eval
) to implement a very silly idea (defining number-based variable).
You can define local variables dynamically on binding
:
b = binding
b.local_variable_set("name_of_variable_#{x}", gets.chomp)
but you would then have to keep carrying that b
around when you want to get the value, and is not convenient.
A slightly better way is to use an instance variable, which does not require you to use a binding:
instance_variable_set("@name_of_variable_#{x}", gets.chomp)
But when you have a sequence of values, especially when they are numbered, there is no reason to keep them each in an individual variable. You should just have a single array that keeps all information:
variables = Array.new(5){|x| print "step #{x + 1}: "; gets.chomp}