Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is << and <<= different in Ruby

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you use an operator op= in Ruby, and the class does not provide a definition for this operator, but has a definition for just op, 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 <<=.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading