Search code examples
ruby-on-railsrubyruby-on-rails-5

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.


Solution

  • 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.