0

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

3
  • In general you can't. There are Binding#local_variable_set//local_variable_set, but this is not exactly what you are looking for. Why do you need it? Commented Oct 26, 2022 at 13:28
  • @KonstantinStrukov it's just a doubt to know if it can be done like in other languages like php. I am new in Ruby Commented Oct 26, 2022 at 13:37
  • You can create instance variables dynamically (i.e. generate the variable name dynamically), and you can use eval, but but both approaches make the code hard to maintain. My feeling is that you have here a XY-problem. Even in PHP, I don't see why you would want to do this for a local variable. Commented Oct 27, 2022 at 7:15

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.