user3260130
user3260130

Reputation: 21

What does Hash[x] << "string" do?

What does Hash[x] << "string" do?

What is the symbol << for and how does it work?

Upvotes: 1

Views: 83

Answers (2)

user2864740
user2864740

Reputation: 62003

The real question is, what does Hash[x] evaluate to?

Because it's that object (an Array, perhaps?) on which the << operator (really a method) is being invoked. That is, Hash[x] << "string" is, excluding the temporary variable, equivalent to t = Hash[x]; t << "string".

Like all overridable Ruby operators1, << is really just a method call. It is commonly seen as Array#<<, but it may be different for the object in question (see above):

[On an Array object, the << operator] Append—Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together.

Once the actual object is known, then the operator can be trivially looked up in the appropriate documentation.


1 See list of ruby operators that can be overridden/implemented for a list; "pure" operators like = (non-indexed assignment) and , cannot be overriden and do not work in the same way.

Upvotes: 5

user513951
user513951

Reputation: 13725

<< is a method that is also usually aliased as append. In Ruby, you can call operator methods in the same way as any other method: an_obj.<<(an_arg) is perfectly valid syntax.

In general, the append method adds the argument to the receiver. If the receiver is an array, it adds the argument to the end of the array; if it's a string, it adds the argument to the end of the string.

The side effects and return value of calling the << method simply depend on the method's implementation in the receiver object's class.

Upvotes: 1

Related Questions