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 trialanthonybrackner
17,776 PointsWhy is the "||" symbol required in stock_count method? Why isn't it simply "@stock_count = 0?"
Title says it all
2 Answers
Jay McGavren
Treehouse TeacherThis is going to sound a little pedantic, but be careful with your terminology... There is no ||
operator present in the code, there's a ||=
operator. ||
, ||=
, and =
are three separate operators with three separate meanings.
=
will assign a new value to a variable, regardless of whether it already contains a value. ||=
will assign a new value only if the variable's current value is nil
.
So if we wrote this:
def stock_count
@stock_count = 0
end
Then every time we called stock_count
, the value of @stock_count
would be reset to 0
, and the stock_count
method would always return 0
. Instead, we write:
def stock_count
@stock_count ||= 0
end
So if a value has never been assigned to @stock_count
before, the stock_count
method will assign it 0
and return 0
. Otherwise (apparently) it will just return the current value of @stock_count
.
It should be noted that this is a slightly unusual way of handling an attribute reader method. Normally, the method would just look like this:
def stock_count
@stock_count
end
...and @stock_count
would be set to 0
in the initialize
method.
anthonybrackner
17,776 PointsThank you Jay
Enrica Fedeli-Jaques
6,773 PointsEnrica Fedeli-Jaques
6,773 PointsThanks a lot for this, Jay McGavren , I think Jason hadn't explained that in the first video when he used it and I was also confused by it. and about being pedantic, well that wasn't pedantic at all, it was an important difference :)