Marcelo Alarcon
Marcelo Alarcon

Reputation: 401

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

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

Upvotes: 0

Views: 324

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21130

In such a scenario it's probably better 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]

Upvotes: 2

Related Questions