Forum: Ruby on Rails Rails Book Source code Question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mark H. (Guest)
on 2005-11-22 22:01
Going through the Rails book samples, on page 68 they have some code
that goes like this:

<%
odd_or_even = 0
for product in @products
  odd_or_even = 1 - odd_or_even
%>

The code works fine for me, but I cannot figure out how the line:

odd_or_even = 1 - odd_or_even

is working?  I mean how does something initialized to zero, then set to
1, then minus one, ever go beyond the value zero?  I just don't under
stand how this is working in Ruby.  It would seem like normally it would
be written like:

if odd_or_even = 1
 odd_or_even = 0
else
 odd_or_even = 1
end

Obviously the way in the book is a shortcut which I have no problem
with, it just doesn't make sense to me.

Thanks.
dteare (Guest)
on 2005-11-22 22:12
(Received via mailing list)
If odd_or_even is 0, then odd_or_even = 1 - odd_or_even is 1.

If odd_or_even is 1, then odd_or_even = 1 - odd_or_even is zero.

Repeat.
Mark H. (Guest)
on 2005-11-22 22:17
dteare wrote:
> If odd_or_even is 0, then odd_or_even = 1 - odd_or_even is 1.
>
> If odd_or_even is 1, then odd_or_even = 1 - odd_or_even is zero.
>
> Repeat.

Thanks, that actually cleared it up 100% for me.  Until it was laid out
like that I just didn't see it working like it was.

-Mark
warrens (Guest)
on 2005-11-23 14:32
(Received via mailing list)
1 - 1 == 0     # 1  ==> 0

1 - 0 == 1     # 0  ==> 1

It flops back and forth from 1 to 0 and back to 1 and then back to 0...

Warren S.
This topic is locked and can not be replied to.