Jinn
Jinn

Reputation: 111

Can someone please explain what (:+) is in Ruby?

Can someone please explain what (:+) is in Ruby? I have tried googling it & looking a reference guides and cant find anything. Thanks, sorry Im pretty new to Ruby & programming.

Upvotes: 1

Views: 771

Answers (2)

Neil Slater
Neil Slater

Reputation: 27207

A colon : before a sequence of characters* is a Symbol literal. This applies to :+, which is a Symbol with content "+".

A symbol can be used to reference a method with the same name in some contexts, and in a couple of places your example :+ can be a reference to the + operator, which is really just a method with the same name. Ruby supports syntax to call it when it sees a plain + in an expression, or in some core methods it will convert :+

As an example you can use :+ as shorthand to create a sum of an Array of integers:

[1,2,3,4].inject( :+ )
 => 10

This works because Ruby has special-cased that specific use of operators in Array#inject (actually defined in Enumberable#inject, and Array gets it from that module).

A more general use-case for a symbol like this is the send method:

2.send( :+, 2 )
=> 4

Although 2.send( "+", 2 ) works just fine too. It might seem odd when used like this instead of just 2 + 2, but it can be handy if you want to make a more dynamic choice of operator.


* The rules for the syntax allowed or not allowed in a Symbol literal are a little arcane. They enable you to write shorter literals where possible, but Ruby has to avoid some ambiguous syntax such as a Symbol with a . or whitespace in the middle. This is allowed, just you have to add quotes if you generate such a Symbol e.g. :"this.that"

Upvotes: 4

Max
Max

Reputation: 22325

Ruby will tell you

:+.class
# Symbol

(:+) is the symbol in parentheses.

Upvotes: 3

Related Questions