randomor
randomor

Reputation: 5663

Iterate through array to construct hash in Ruby

Currently I have:

cache_hash = {}
array = [:id, :content, :title]
data_source = some_active_record_object
array.each{ |k| cache_hash[k] = data_source.send(k) } 
cache_hash
#=>{:id=>"value1", :content=>"value2", :title=>"value3"}

I'm wondering if there is a better way to iterate through the array and get the hash out.

Upvotes: 1

Views: 88

Answers (3)

user456814
user456814

Reputation:

This is similar to @Arup's answer using map. The cool thing about map functions, in any programming language (not just Ruby), is that you can also express them in terms of an inject function (also called fold, reduce, or aggregate in other languages):

cache_hash = array.inject({}) do |hash, key|
  hash[key] = data_source.send key
  hash
end

Not as clear as Arup's answer using map, but kind of cool to know anyways.

Upvotes: 1

vee
vee

Reputation: 38645

I'm not sure if you want to follow this route, but here is an alternative with AR query:

Foo.select('id, content, title').to_a.map(&:serializable_hash)

Foo is the model you're operating on.

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

Write as below :

cache_hash = Hash[array.map { |k| [k, data_source.send(k)] }]

Or use new #to_h

cache_hash = array.map { |k| [k, data_source.send(k)] }.to_h

Upvotes: 4

Related Questions