简体   繁体   中英

What is map(&:id) in Rails?

My question is not an error, it is for understanding. As I'm new to Rails, I can't read all the code yet.

  1. what does (&:id) do after .map

    @user_cnae_classifications = user.cnae_classifications.map(&:id)

    what is the difference of .map with it and without it?

  2. in this method call:

     UserCnaeClassification.create( user: @user, cnae_classification_id: id )

    How do I read that part of the code...

     user: @user, cnae_classification_id: id

    are they keys and values?

1 ) You should read some tutorials on map to get acquainted. https://www.rubyguides.com/2018/10/ruby-map-method

But the short answer is that running user.cnae_classifications.map(&:id) will loop over all cnae_classifications and extract the id from them and put them all into an array. The & character allows for map shorthand to avoid passing an entire block.

From the link above: Ruby Map 方法图

2 ) The #create method can accept a key-value hash of known attributes (known to the class in question, in this case that is UserCnaeClassification ) to assign upon creation. So you're basically right, they are key-value pairs but they are specific to this class/object. Those same keys might not work on another class/object. Additional reading:https://guides.rubyonrails.org/active_record_basics.html#create

  1. what does (&:id) do after .map

The syntax map(&:method) is equivalent to:

object.map do |i|
   i.method
end

The complete explanation is that the & operator is used to convert any Ruby object that responds to to_proc into a Proc , which encapsulates a block of code. In this case, the Symbol object ( :id ) is converted into the block of code above.

If you're interested in learning more about it, notice this is pure Ruby , not Rails-specific. Check the documentation for Proc .

  1. In this method call: How do I read that part of the code... are they keys and values?

These are keyword arguments . It's a way to name the parameters of a method to explicitly tell the reader what each value should be. Just be aware that the behavior of methods accepting hashes as keyword arguments is deprecated, as seen in this official post .

The .map(&:id) is a shorthand for the longer form of .map { |x| x.id } .map { |x| x.id } .

Some interesting things to say: if you're using database (ORM - ActiveRecord), you will see that writing map(&:id) could be helpful. There also exists method called pluck, which does similiar things, but it's a little faster.

在此处输入图像描述

在此处输入图像描述

Usage: 在此处输入图像描述 Also pluck doesn't work with regular Arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM