[Rails] Some enumerable methods and Hash

Tags
Rails
Engineering
Created
Oct 10, 2023 03:40 AM
Edited
Oct 10, 2023
Description
pluck/select/Hash/map/to_h/index_by

Pluck

pluck(*column_names) public
  • Use #pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.
  • Returns an array with the type of the column you specify
Person.pluck(:name)
# SELECT people.name FROM people
# => ['David', 'Jeremy', 'Jose']

Person.pluck(:id, :name)
# SELECT people.id, people.name FROM people
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

Person.distinct.pluck(:role)
# SELECT DISTINCT role FROM people
# => ['admin', 'member', 'guest']

Person.where(age: 21).limit(5).pluck(:id)
# SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
# => [2, 3]

Person.pluck('DATEDIFF(updated_at, created_at)')
# SELECT DATEDIFF(updated_at, created_at) FROM people
# => ['0', '27761', '173']

pick

  • pluck(:id).first is the same as pick(:id)

select

  • Pretty much like pluck but returns an ActiveRecord::Relation
Person.select(:id)
# SELECT people.id FROM people

Hash

  • {}
h = Hash.new
h.default# => nil

h = Hash.new(-1)
h.default # => -1
h.default = 0
h.default # => 0

map

  • Returns an array based on the custom lambda logic
array = ["a", "b", "c"]
array.map { |string| string.upcase }
# ["A", "B", "C"]

to_h

  • Returns a hash
  • A nice way to build a hash with map on ActiveRecord::Relation
hash = { bacon: "protein", apple: "fruit" }
hash.map { |k,v| [k, v.to_sym] }.to_h
# {:bacon=>:protein, :apple=>:fruit}

# Ruby 2.1+
name_to_code = countries.map{ |c| [c.name,c.code] }.to_h

index_by

  • To create a hash from ActiveRelation, and values are each ActiveRecord and we can define the key mostly from the attributes or associated records
  • Like the combination of map and to_h
people.index_by(&:login)
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
people.index_by { |person| "#{person.first_name} #{person.last_name}" }
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}

Source