I have code:
def make_all_thumbs(source)
sizes = ['1000','1100','1200','800','600']
threads = []
sizes.each do |s|
threads << Thread.new(s) {
create_thumbnail(source+'.png', source+'-'+s+'.png', s)
}
end
end
what does << mean?
It can have 3 distinct meanings:
‘<<‘ as an ordinary method
In most cases ‘<<‘ is a method defined like the rest of them, in your case it means "add to the end of this array" (see also here).
That’s in your particular case, but there are also a lot of other occasions where you’ll encounter the "<<" method. I won’t call it ‘operator’ since it’s really a method that is defined on some object that can be overridden by you or implemented for your own objects. Other cases of ‘<<‘
Singleton class definition
Then there is the mysterious shift of the current scope (=change of self) within the program flow:
The mystery
class << selfmade me wonder and investigate about the internals there. Whereas in all the examples I mentioned<<is really a method defined in a class, i.e.is equivalent to
the
class << self(or any object in place of self) construct is truly different. It is really a builtin feature of the language itself, in CRuby it’s defined in parse.y ask_classis the ‘class’ keyword, wheretLSHFTis a ‘<<‘ token andexpris an arbitrary expression. That is, you can actually writeand will get shifted into the singleton class of the result of the expression. The
tLSHFTsequence will be parsed as a ‘NODE_SCLASS’ expression, which is called a Singleton Class definition (cf. node.c)Here Documents
Here Documents use ‘<<‘ in a way that is again totally different. You can define a string that spans over multiple lines conveniently by declaring
To distinguish the ‘here doc operator’ an arbitrary String delimiter has to immediately follow the ‘<<‘. Everything inbetween that initial delimiter and the second occurrence of that same delimiter will be part of the final string. It is also possible to use ‘<<-‘, the difference is that using the latter will ignore any leading or trailing whitespace.