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

method syntax

Ruby's built in methods like .length & .upcase & .capitalize are called like "like this".length where the method comes after. Why when creating your own method it comes after like add(1, 2) apposed to (1, 2).add?

1 Answer

Jeremy Hamilton
Jeremy Hamilton
7,229 Points

That is not entirely true. The difference you're looking at are class methods and instance methods. Instance methods are ones that are put up at the base (object) level of the code and class methods are methods that are applied on the class level. An example of a class method is:

class Example
  def Example.class_method
    #This is where the def text goes for example.class_method
  end
end

#after here the example() class can be utilized with the example.class_method class method.

Class methods can not be accessed by other classes or the instances (with few exceptions).

And an example of an instance method (what you're probably thinking of when you generally refer to a method) is as follows:

def Example
  puts "This is an instance method!"
end

TL;DR: You can have methods that work that way too but they only apply to specific classes. The example you mentioned, the .length method is a class method of the String class in the ruby default classes.