0

I have an array and hash which I need to combine. Please let me know the simplest way to do this.

array1 = [:user_id, :project_id, :task_id]

entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87]}

When it is combined i want a hash like

output = {"user_id"=>1, "project_id"=>8, "task_id"=>87}

Thanks for the help!

Archie123
  • 105
  • 2
  • 13

1 Answers1

0

It's a bit unclear to me what you want to achieve here. Looking at your example, the easiest solution would be to change the keys of entry_hash using .downcase and adding _id. For the value, you could check if it's an array and if so, use the first value.

output = {}

entry_hash.each do |key, value|
  output[key.downcase + '_id'] = value.kind_of?(Array) ? value[0] : value
end

This assumes of course that the keys in the hash are the nouns for the column names in the array. The code above will not work if the names are more complex (e.g. CamelCaseName or snake_case_id). Rails comes with ActiveSupport that can help you there, but this is a totally different question: Converting camel case to underscore case in ruby

If array and hash don't share the same names there is no easy way to do this automatically. Hash doesn't guarantee the order of its elements, so iterating through both and mapping values like in the above snippet won't work reliably.

jdno
  • 4,104
  • 1
  • 22
  • 27