Home > Software engineering >  What is << and <<= different in Ruby
What is << and <<= different in Ruby

Time:03-11

I am a newbie about Ruby on Rails. I know << operator what it is doing but I am working with datatable and I have codes like these:

def data
    items.map do |donation|
      [].tap do |column|
        column << donation_path(donation)
        column <<= current_user.admin? ? link_to(donation.sender.name, admin_store_path(donation.sender)) : donation.sender.name 
      end
    end
  end

I tried to <<= in rails c and the result is:

irb(main):001:0> ar = []
=> []
irb(main):002:0> ar << 1
=> [1]
irb(main):003:0> ar <<= 1
=> [1, 1]
irb(main):004:0> ar <<= 2
=> [1, 1, 2]

I think <<= is similar with << but I have to be sure.

CodePudding user response:

If you use an operator op= in Ruby, the expression

x op= y

is equivalent to

x = x op y

In your case, it means that an

a <<= b

is equivalent to

a = a << b

but since a << b already modifies a, you gain nothing from using <<=.

NOTE: As was pointed out in the comments, this does not apply for the operator []: If you want to have an assignment version, you have to define []= explicitly.

  • Related