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 Ruby Modules Ruby Core Modules Math

Math::sqrt(9) vs Math.sqrt(9)

So this is kind of tripping me up a bit. Running puts Math::sqrt(9) and puts Math.sqrt(9) both return 3.0. It seems that sqrt is both a method inside the Math module and a method inside the Math class. Why are there two methods for sqrt?

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

It seems that sqrt is both a method inside the Math module and a method inside the Math class.

Not quite, Ruby only comes with one sqrt() method, and it's defined at the Math module. Math::sqrt(9) and Math.sqrt(9) have no difference, Ruby allows you to use these 2 notations interchangeably when calling the instance method, though, by convention, dot notation is the preferred way.

However, you have to use the :: notation to access the constants, nested modules, or non instance methods defined within module/class.