user1513388
user1513388

Reputation: 7441

Ruby re-structuring data

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

Answers (2)

Andrea Fiore
Andrea Fiore

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

megas
megas

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

Related Questions