Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Unfamiliar use of symbol with operator.

I ran across a line of code with an unfamiliar symbol/operator - (:*)

Here it is in context:

(1..num).inject(:*) || 1

I understand the output returns a factorial, but can anyone explain the colon's function and relation to the multiply operator?

1 Answer

The colon ":" tells Ruby to apply the subsequent operator (i.e. use it as a method) to the successive elements of the collection created/built by the #inject (aka #reduce) method. So the given snippet of code is a shorthand form (aka syntactic sugar) of the following:

(1..num).inject { |product, factor| product * factor } || 1

Start an irb session in your Terminal and try it. You should get the same answer using either form.