Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the `<<` (double less than) mean without an argument?

I found this inside a method I want to override in the formtastic Gem. The method looks like:

def to_html
  input_wrapping do
    hidden_field_html <<
    label_with_nested_checkbox
  end
end

What does the << do on the third line? I know what it does with Arrays but here I have no idea.

like image 521
Peter Piper Avatar asked Jul 26 '16 08:07

Peter Piper


People also ask

What does double less than mean?

The double less-than sign, <<, may be used for an approximation of the much-less-than sign (≪) or of the opening guillemet («). ASCII does not encode either of these signs, though they are both included in Unicode.

What is the meaning of this ≥?

The symbol ≥ means greater than or equal to.

What is the meaning of symbol less than?

The less-than sign is one of the inequality signs, which is used to compare the number. If the first number is less than the second number, less sign is used. For example, 5 < 10. It means that the number 5 is less than the number 10.

What is the meaning of the statement less than?

phrase. You use less than to say that something does not have a particular quality. For example, if you describe something as less than perfect, you mean that it is not perfect at all.


2 Answers

You can read it like this:

hidden_field_html << label_with_nested_checkbox

label_with_nested_checkbox is the argument being concatenated onto the end of hidden_field_html - they've split it over two lines for 'clarity'

like image 101
stephenmurdoch Avatar answered Oct 03 '22 11:10

stephenmurdoch


  1. In class inheritance there is < used, not <<, and the former has nothing to do with method << in general.

  2. Ruby has a high level of tolerance to space indenting; almost everywhere one might put any amount of spaces, including newlines, between function call and it’s argument.

E. g.:

'aaa'.
  length
#⇒ 3

and

'aaa'
  .length
#⇒ 3

are both perfectly valid.

  1. << is the generic method, that might be overwritten in any class. Here it is supposedly String#<< method, that inplace appending the argument to the string receiver.

In general, one might overwrite this method in any arbitrary class:

class A
  attr_accessor :var
  def initialize
    @var = 5
  end
  def << value
    @var += value
  end
end

a = A.new
a.var
#⇒ 5
a << 37
a.var
#⇒ 42
like image 33
Aleksei Matiushkin Avatar answered Oct 03 '22 10:10

Aleksei Matiushkin