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 trialAntoine Boillot
10,466 PointsWhy 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
Maciej Czuchnowski
36,441 PointsIt's a so-called syntactic sugar. Other important keywords here are, as Ethan mentioned - setter and getter methods. These links will probably help you more than my attempt at explaining this:
http://rubylearning.com/satishtalim/ruby_syntactic_sugar.html
http://stackoverflow.com/questions/8737421/trying-to-learn-understand-ruby-setter-and-getter-methods
Ethan Lowry
Courses Plus Student 7,323 PointsThat 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
10,466 PointsCrystal clear. Thanks a lot.