1

Couldn't find this specific instance anywhere; I might be missing something simple, but here it goes.

Say I have an array:

["Field1", "Field2"]

I need to convert this into an array of hashes, as such (the FieldType key/value is a default value)

[{"Name"=>"Field1", "FieldType"=>"Text"}, 
 {"Name"=>"Field2", "FieldType"=>"Text"}]

How would I go about doing this? The below clearly doesnt work:

fields.each do |field|
  fieldResults << {"Name" => field, "FieldType" => "Text"}
end

4 Answers 4

9

Assuming fieldResults is an array, what you wrote should work, though it's more idiomatic to use a better-suited function, like map.

fields.map {|field| { 'Name' => field, 'FieldType' => 'Text' }}
Sign up to request clarification or add additional context in comments.

2 Comments

map worked, for whatever reason I couldn't get my code (above) to work. Thank you!
took me forever to find this result on google even with the search "convert array into array of hashes". Thank goodness I finally found your answer!
1

If fields = ["Field1", "Field2"] and fieldResults is initialized to [] your code should work. But as Chuck said fieldResults = fields.map {|field| { 'Name' => field, 'FieldType' => 'Text' }} is more ideomatic.

By the way: The ruby naming convention for symbols, methods and variables is to use snake_case (underscores) rather than camelCase for multiple word names. Like field_results instead of fieldResults

Comments

0

You can take the below approach too :

fields = ["Field1", "Field2"]
result = fields.map{|i| {"Name" => i}.update({"FieldType" => "Text"})}
# => [{"Name"=>"Field1", "FieldType"=>"Text"},
#     {"Name"=>"Field2", "FieldType"=>"Text"}]

Comments

0

Another way of doing this.

fieldResults = []
["Field1", "Field2"].each{|e| fieldResults << Hash["Name",e,"FieldType","Text"]}
1.9.3 (main):0 > fieldResults
 => [{"Name"=>"Field1", "FieldType"=>"Text"},
    {"Name"=>"Field2", "FieldType"=>"Text"}]

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.