0

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.

4
  • 2
    arr[0] = "user.#{arr[0]}" or arr[0].prepend('user.') or arr[0].insert(0,'user.') or ...? Commented Nov 30, 2022 at 19:12
  • @engineersmnky I tried this but then it is no more an array: "user.email" ..This is what it returned Commented Nov 30, 2022 at 19:14
  • arr = ["first_name"]; arr[0].prepend('user.'); arr #=> ["user.first_name"] <- updates the string inside the array. You you have to do this a bunch of times then arr.map(&'user.'.method(:+)) would work too and will return a new array Commented Nov 30, 2022 at 19:16
  • @engineersmnky your first comment way right, you want to write it as an answer? Commented Nov 30, 2022 at 19:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.