Home > database >  How do I concatenate a string to a variable declaration in Ruby?
How do I concatenate a string to a variable declaration in Ruby?

Time:10-27

I wonder if it is possible to concatenate a variable value or a string to a new variable value declaration in Ruby.

foo = "something"
#new variable declaration:
var_   foo = "concat variable name"
p var_foo   # => "concat variable name"

n = 2
position   n = Array.new(3, 1)
p position2    # => [1, 1, 1]`

Thank you very much

CodePudding user response:

In such a scenario it's probably best to use a Hash instead.

values = {}
values['foo'] = 'something'
values['var_'   'foo'] = 'concat variable name'

p values['var_foo'] #=> "concat variable name"

n = 2
values["position#{n}"] = Array.new(3, 1)
p values['position2'] #=> [1, 1, 1]
  • Related