Home > Enterprise >  how to concat string to array element in rails
how to concat string to array element in rails

Time:12-01

I have an array as

["first_name"]

and I want to convert it to

["user.first_name"]

I cannot figure out how I can do this in rails.

CodePudding user response:

If you would like to append text to the values you have in a array you're going to probably want to loop through the data and append to each element in the array like so:

my_array = ["test", "test2", "first_name"]
new_array = my_array.collect{|value| "user.#{value}" }

new_array will now be:

["user.test", "user.test2", "user.first_name"]

You could also just overwrite your original array by using collect! like so

my_array = ["test", "test2", "first_name"]
my_array.collect!{|value| "user.#{value}" }

This will of course overwrite your original original data in my_array

If you would like to just change one value in the array you could use the index of that array and assign the value

my_array = ["test", "test2", "first_name"]
my_array[1] = "user.#{my_array[1]}}

my_array will now read:

["test", "user.test2", "first_name"]

CodePudding user response:

Supposing you've multiple elements in your array, I recommend using .map.

It allows you to iterate the array elements, and return a new value for each of them.

%w[first_name last_name email].map do |attr|
  "user.#{attr}"
end
# => [user.first_name, user.last_name, user.email] 
  • Related