3

I want to create dynamic variable and assign values to them. Here is quick sample what I tried so far.

array = %w(this is a test)
array.each_with_index do |c,v|
  puts "variable_#{v}".to_sym
end

which gives me output like this:

# variable_0
# variable_1
# variable_2
# variable_3

But when I am trying to assign value like below:

array.each_with_index do |c,v|
  puts "variable_#{v}".to_sym = 45 # I want to assign value which will be result of api, here I just pass 45 static
end

this gives me an error:

undefined method `to_sym=' for "variable_0":String (NoMethodError)

If I removed .to_sym it gives me an error like:

syntax error, unexpected '='

Please help me. How can I achieve this? Thanks in advance.

Note: This is just a sample code to understand how to create dynamic variables and assign them variable. In my app it's a instance_variable and I want to use them to achieve my goal.

Hetal Khunti
  • 787
  • 1
  • 9
  • 23
  • Have you considered using a Hash? You could have an Instance Hash and assign to it any value you like with dynamic key names. – pedros May 18 '15 at 10:57
  • I wanted to loop with these variable, so I think Can I do it using hash key? – Hetal Khunti May 18 '15 at 10:59
  • You can't do that without initializing that variable outside that block. Because otherwise it will not be accessible outside of that block. You should use enumerator to save result list. – Anuja May 18 '15 at 11:01
  • @Anuja : Can you show some example? I appreciate – Hetal Khunti May 18 '15 at 11:01
  • possible duplicate of [Dynamically set local variables in Ruby](http://stackoverflow.com/questions/4963678/dynamically-set-local-variables-in-ruby) – Lukas Baliak May 18 '15 at 15:41
  • Your code seems to be setting local variables (e.g. `foo`), but your note says you want to set an instance variable (e.g. `@foo`). I'm not sure what it is you want to do. – Wayne Conrad May 18 '15 at 21:31

2 Answers2

2

Considering that you really need to set instance variable dynamically, instance_variable_set may help you.

array.each_with_index do |c,v|
  instance_variable_set "@variable_#{v}".to_sym, 45 # `@` indicates instance variable
end
RAJ
  • 9,697
  • 1
  • 33
  • 63
1

You can collect result in array or hash. Its difficult to give example with partial info. But in array you can collect result as follows:

result_set = array.collect do |c|
  45
end

Which will give you

result_set = ["this", "is", "a", "test"]

For hash let me know what type of key and value you want to collect so that I can give you particular example. I hope this will help you.

Anuja
  • 646
  • 4
  • 14
  • Thanks for your solution but then I realized it will become more complicated so I plan to make new function and pass dynamic name of variable.. anyways thanks – Hetal Khunti May 18 '15 at 11:37
  • Welcome. But I didn't get the actual requirement. I hope you got solution for your problem. – Anuja May 18 '15 at 14:16