Posts tagged "unary"

Pratik lately is doing a great work refactoring ActiveRecord to make a full use of relations. Speaking in code language, this means that in Rails 3 you will be able to do:

  User.where(:name => "Jose").order("birthday")

And it will return a relation. The relation can be further manipulated and the query is only triggered when you call all, first, to_a or some Enumerator method.

Besides that, he’s also doing some crazy experiments, which will probably become a plugin later. While discussing with Pratik some ways to implement equality and inequality, I discovered a neat ruby trick. Open up an irb session and do:

MD7M9TSHSAJY
~2  #=> -3
~42 #=> -43

And this method is actually documented.

The nice thing though, is that you can define this method in other classes as well. In the querying scenario for example, we could add this behavior:

class Symbol
  def ~
    :"LOWER(#{self})"
  end
end

And now we could actually do:

User.where(~:email => "jose@plataformatec.com.br")
#=> SELECT * WHERE LOWER(email) = "jose@plataformatec.com.br"

Unary operators

Yehuda Katz later pointed to me that this can actually be done with any of the three unary operators in Ruby: +, – and ~.

So we could also do:

class String
  def +@
    upcase
  end
 
  def -@
    downcase
  end
end

And now:

+"jose" #=> "JOSE"
-"JOSE" #=> "jose"

You could even “go crazy” and append several unary operators:

+-+"jose" #=> "JOSE"

And you? Did you know such behavior in Ruby? Do you have any good use case for it?