The regular AR pluck method returns the values only, for instance: 
Student.pluck(:firstname) => ["John", "Mike", "Simon"]

It'd be a nice feature to have a version which returns a hashes with the 
column names as keys: [{ firstname: "John"}, { firstname: "Mike" }, { 
firstname: "Simon" }]

I know this can (almost) be achieved with 
Student.select(:firstname).map(&:attributes) (it forces you to have an id 
attribute), but this involves instantiating lots of AR objects, which loses 
the benefit of pluck.

An example implementation would be:

def self.hash_pluck(*keys)
  pluck(*keys).map{ |vals| Hash[keys.zip(Array(vals))] }
end

In some (probably bad) benchmarks I made comparing this to the select 
alternative, the select method was ~3.4x slower.

Benchmark.ips do |x|
  x.report("hash_pluck") { Student.hash_pluck(:firstname) }
  x.report("select") { Student.select(:firstname).map(&:attributes) }
  x.compare!
end

Calculating -------------------------------------
              select     6.000  i/100ms
          hash_pluck    24.000  i/100ms
-------------------------------------------------
              select     77.096  (±29.8%) i/s -    342.000 
          hash_pluck    265.316  (±41.8%) i/s -      1.104k

Comparison:
          hash_pluck:      265.3 i/s
              select:       77.1 i/s - 3.44x slower

Just thought that it might be a nice convenience method to have!

Cheers,
Mike

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Reply via email to