Home > Software engineering >  assigning values of array into variables in ruby
assigning values of array into variables in ruby

Time:02-15

I am trying to assign the each value of an array into different variables. But I am getting error as "Expecting end."

strs = ["flower","flow","flight"]
strs.each_with_index do |x, i|
"b#{i}" = x
end

what is going wrong here ?

CodePudding user response:

What you're doing is like saying

"howdy" = 1

You can't say that. That expression attempts to assign into a string literal. You can't do that. A string literal is not an lvalue (a thing that can go on the left side of an equal sign).

If you are trying to say "make a variable called howdy and assign this value to it", you can't do that because local variables cannot be created on the fly. See How to dynamically create a local variable?.

However, the real core of your issue is that you should not even want to do what you're doing. You already have an array, a wonderful thing that allows you to reference each entry by number. "flower" in your code is already strs[0], and so on. The whole point of the array is that it lets you do that. There is thus no need for individual variables with number names; the array is the variable with number names.

CodePudding user response:

I'm not sure as to WHY you are attempting to create local variables when you already sort of have them. Consider the following where we simply replace your suggested b0 with b[0]:

strs = ["flower","flow","flight"]
b = strs
b[0]  #=>  "flower" 

You could optionally convert your array to a hash using an approach similar to what you've already tried and replace b0 with b[0]:

b = {}
strs.each_with_index do |x, i|
  b[i] = x
end

b[0]  #=>  "flower"

Or even something like this:

my_variables = {}
strs.each_with_index do |x, i|
  my_variables[:"b#{i}"] = x
end

my_variables[:b0] #=>  "flower"
  • Related