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 Foundations Methods Instance Methods

Antoine Boillot
Antoine Boillot
10,466 Points

Why do I have to type [def name=(str)] in the following method example ?

Hi all,

I am currently following the Ruby Foundations.

I noticed a syntax that Jason is using while creating a method in the Modules section, that I cannot remember having seen in the Method one.

Here is an example :

def name=(str)
    @name = str
end

Why is this "=" used for ?

I would have type the following (even though I tested it and it's not working) :

def name(str)
    @name = str
end

Generally speaking, when should I use one or the other of the following syntaxes ?

def method_name(item)

# OR

def method_name=(item)

Thanks a lot for your help ! :)

Cheers,

3 Answers

Ethan Lowry
PLUS
Ethan Lowry
Courses Plus Student 7,323 Points

That syntax is used for setter functions - you don't actually see it written very often because usually in Ruby getters and setters are created for you via helpers like attr_accessor.

It simply means that you're able to do person.name = 'Antoine', for example.

Antoine Boillot
Antoine Boillot
10,466 Points

Crystal clear. Thanks a lot.