Reputation: 7441
I need to build an array of hashes that looks like this:
[
{:name=>"company", :value=>"Microsoft"},
{:name=>"type", :value=>"software"},
{:name=>"country", :value=>"US"},
{:name=>"valid", :value=>"yes"}
]
Rather than having to keep defining the name and value fields I've built a helper function that looks like this:
def build(attributes=[])
list = []
attributes.each {|k,v| list.push({:name=> "#{k}", :value=> "#{v}"})}
list
end
I can then simply create my array like this:
attribs = { :company => 'Microsoft', :type => 'software', :country=> 'US', :valid=> 'yes'}
puts build(attribs).inspect
#[{:name=>"company", :value=>"Microsoft"}, {:name=>"type", :value=>"software"}, {:name=>"country", :value=>"US"}, {:name=>"valid", :value=>"yes"}]
This seems a litte inefficient and verbose for Ruby! Is there a cleaner or more efficient way to achieve this result?
Regards,
Carlskii
Upvotes: 0
Views: 56
Reputation: 1638
You can also use Ruby's Hash.[] method, which accepts an even number of arguments as key value pairs:
Hash['company', 'microsoft','type','software','country','us']
#=> {"company"=>"microsoft", "type"=>"software", "country"=>"us"}
This is often used in conjunction with Ruby's splat operator, which lets you pass an array as the method arguments.
attributes = ['company', 'microsoft','type','software','country','us']
Hash[*attributes]
#=> {"company"=>"microsoft", "type"=>"software", "country"=>"us"}
Upvotes: 0
Reputation: 21791
I assumed that attributes has these kind of data:
attributes = [['company','Microsoft'],...]
Then to build hash from that:
attributes.map { |k,v| {:name => k, :value => v} }
#=> [{:name=>"company", :value=>"Microsoft"},...
Upvotes: 1