Search code examples
rubyvariablesgenerated

Create a new variable from generated element


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.


Solution

  • 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).