Hetal Khunti
Hetal Khunti

Reputation: 807

How to define dynamic variable and assign it to some value in rails

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.

Upvotes: 3

Views: 4125

Answers (2)

RAJ
RAJ

Reputation: 9747

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

Upvotes: 2

Anuja
Anuja

Reputation: 654

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.

Upvotes: 1

Related Questions