1

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.

2
  • Thanks for all your input. I know it's not fair to select a rails specific answer. But I do appreciate the lesson from @Arup too. Commented Mar 23, 2014 at 21:02
  • No, it was completely fair, as you tagged it with ruby-on-rails and therefore a Rails answer is appropriate. Commented Mar 23, 2014 at 23:16

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

That's very interesting. Since I'm targeting only one object, not an array, here is what I ended up with: data_source.serializable_hash(only: [:id, :content]).
1

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.

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.