Missing space leads to different result


Yesterday I introduced a bug in one of my scripts after accidentally
deleting av space. It took me quite I while to find where the bug was,
but I still can’t understand why the missing space leads to a
different result. Anyone out there that can explain it to me?

[email protected]:~$ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]

[email protected]:~$ irb
irb(main):001:0> elems = [‘foo’, ‘bar’, ‘baz’]
=> [“foo”, “bar”, “baz”]
irb(main):002:0> puts elems.count -1
=> nil
irb(main):003:0> puts elems.count - 1
=> nil

How does the missing space between the minus sign and the number 1
change the expression?

Any answers appreciated


Removing the space causes the minus to be interpreted as a unary
operator rather than the binary minus that you get with the space. The
unary operator has a relatively higher precedence than the binary minus
more importantly than the dot operator used for invoking #count on your
array, so it changes the expression evaluation completely – first,
evaluating the unary negative operator on 1, and then passing the result
an argument to #count. Because Array#count can take an argument that
“count how many of this thing I have in my array”, you get 0 as your
because your array has no -1 elements. See how the result changes below
when I begin adding -1’s to my array.

ruby-1.9.2-p0 :001 > elems = [“a”, “b”, “c”]
=> [“a”, “b”, “c”]
ruby-1.9.2-p0 :002 > elems.count - 1
=> 2
ruby-1.9.2-p0 :003 > elems.count -1
=> 0
ruby-1.9.2-p0 :004 > elems << -1
=> [“a”, “b”, “c”, -1]
ruby-1.9.2-p0 :005 > elems.count -1
=> 1
ruby-1.9.2-p0 :006 > elems << -1
=> [“a”, “b”, “c”, -1, -1]
ruby-1.9.2-p0 :007 > elems.count -1
=> 2


It seems like I’ve been using ruby for six years without ever
realizing that Enumerable.count behaved differently than
Enumerable.length or Enumerable.size. Those nifty enumerators usually
make it unnecessary to deal with the index at all.

I’ll just switch to Enumerable.size for now. That will give me an
argument error if I’ll ever drop that space again. :slight_smile:

Thanks again for enlightening me!


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs