What does &:title mean in Model.all.map(&:title)?

Asked 2 years ago, Updated 2 years ago, 28 views

There's a model in Rails What does Model.all.map(&:title) mean?

The map in the Ruby array [1, 2, 3].I've written map { |n| n * n} #=> [1, 4, 9] before.

ruby-on-rails ruby

2022-09-22 22:00

2 Answers

Model.all.map(&:title) behaves the same as Model.all.map{ |o| o.title}.

In ruby, if the parameter has &, expect the object to be Proc, but if the object is not Proc, call the object's to_proc method to convert it to Proc. Because :title is a Symbol object, :title.to_proc is called to convert it to Proc where Symbol#to_proc allows you to invoke a method corresponding to the Symbol name. That's why it's doing the same thing as Model.all.map{ |o| o.title}.

For your information, Symbol#to_proc first appeared in Ruby On Rails' ActiveSupport, which was officially included in Ruby 1.8.7. The internal implementation is as follows.

class Symbol
  # # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples:
  #
  #   #   # The same as people.collect { |p| p.name }
  #   #   people.collect(&:name)
  #
  #   #   # The same as people.select { |p| p.manager? }.collect { |p| p.salary }
  #   #   people.select(&:manager?).collect(&:salary)
  def to_proc
    Proc.new { |obj, *args| obj.send(self, *args) }
  end
end


2022-09-22 22:00

Looking up, the following expression is

Model.all.map(&:title)

The following abbreviation (shortened) expression is called:

Model.all.map { |m| m.title }

As a result, I think it will be made into an array by combining only the attributes title.

Simple Test Example

class TEST
  attr_reader :title
  attr_reader :number
  def initialize(title,number)
    @title = title
    @number = number
  end
end
m1 = TEST.new("A",1)
m2 = TEST.new("B",2)
m3 = TEST.new("C",3)

model = [m1,m2,m3]

print model.map(&:title)  #=> ["A","B","C"]


2022-09-22 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.