user12763413
user12763413

Reputation: 1347

how to concat string to array element in rails

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.

Upvotes: 0

Views: 480

Answers (2)

Jesse Antunes
Jesse Antunes

Reputation: 121

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"]

Ruby doc info: https://ruby-doc.org/3.2.2/Array.html#method-i-collect

collect and map are alias for each other fyi.

Upvotes: 3

Sumak
Sumak

Reputation: 1051

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] 

Upvotes: 0

Related Questions