What does << mean in Ruby?

前端 未结 8 658
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 12:13

I have code:

  def make_all_thumbs(source)
    sizes = [\'1000\',\'1100\',\'1200\',\'800\',\'600\']
    threads = []
    sizes.each do |s|
      threads <         


        
8条回答
  •  我在风中等你
    2020-12-04 12:18

    In ruby '<<' operator is basically used for:

    1. Appending a value in the array (at last position)

      [2, 4, 6] << 8 It will give [2, 4, 6, 8]

    2. It also used for some active record operations in ruby. For example we have a Cart and LineItem model associated as cart has_many line_items. Cart.find(A).line_items will return ActiveRecord::Associations object with line items that belongs to cart 'A'.

    Now, to add (or say to associate) another line_item (X) to cart (A),

    Cart.find(A).line_items << LineItem.find(X)
    
    1. Now to add another LineItem to the same cart 'A', but this time we will not going to create any line_item object (I mean will not create activerecord object manually)

      Cart.find(A).line_items << LineItem.new

    In above code << will save object and append it to left side active record association array.

    And many others which are already covered in above answers.

提交回复
热议问题