Strange ruby ​​amount behavior on rails console

Has anyone noticed something like this? Why is this 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

Additional materials:

 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' ... 
+4
source share
1 answer

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

First:

 "ayay".length + 1 

looks like

 "ayay".length.+(1) 

And the second:

 "ayay".length +1 

looks like

  "ayay".length(+1) 

This way you can understand 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.

+5
source

Source: https://habr.com/ru/post/1383615/


All Articles