Question

Have anyone noticed something like this? Why is it happening?

ruby-1.9.2-p290 :006 > User.count
   (0.4ms)  SELECT COUNT(*) FROM "users" 
 => 102 
ruby-1.9.2-p290 :007 > User.count + 1
   (0.4ms)  SELECT COUNT(*) FROM "users" 
 => 103 
ruby-1.9.2-p290 :008 > User.count+ 1
   (0.4ms)  SELECT COUNT(*) FROM "users" 
 => 103 
ruby-1.9.2-p290 :009 > User.count+1
   (0.4ms)  SELECT COUNT(*) FROM "users" 
 => 103 
ruby-1.9.2-p290 :010 > User.count +1
   (0.5ms)  SELECT COUNT(1) FROM "users" 
 => 102 

Using ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux] && Rails 3.1.3

Extra stuff:

ruby-1.9.2-p290 :007 > "ayay".length + 1
 => 5 
ruby-1.9.2-p290 :008 > "ayay".length +1
ArgumentError: wrong number of arguments(1 for 0)
    from (irb):8:in `length'
    ...
Was it helpful?

Solution

This depends on the fact that in Ruby white spaces can be significant. You see different results because Ruby interprets your example in different ways. So

The first:

"ayay".length + 1

is like

"ayay".length.+(1)

And the second:

"ayay".length +1

is like

 "ayay".length(+1)

In this way you can see why Ruby gives an error in the second case.

Regarding the count problem: Ruby interprets the code as:

User.count(+1)

And, as you can see from the generated SQL, there is a difference because +1 is considered the column_name parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top