This article is quite old.Time flies when you're having fun. I've been writing for my blog for a long time. Stuff changes fast, especially in the Ruby world. That's why I've put this warning on old posts. The article might still be valid, though.
I recently encountered some methods I didn't know about.
The tilde method (
~) is used by Sequel and you can use it like this:
class Post def ~ 11 end end post = Post.new ~post # => 11
That's right: you call this method by placing the tilde before the object.
In Sequel it is used to perform NOT queries, by defining the tilde on Symbol:
Post.where(~:deleted_at => nil) # => SELECT * FROM posts WHERE deleted_at IS NOT NULL
The minus-at (
-@) method works just about the same as the tilde method. It is the method called
when a minus-sign is placed before the object. In effect, this means that Fixnum is
implemented somewhere along the lines of this:
class Fixnum def -@ self * -1 end end num = 10 negative = -num # => -10
I found this one browsing through the source of the
ActiveSupport::Duration class (you know, the one you get when you do
1.day). I guess it makes
Be careful with chaining methods though:
ruby-1.9.1-p378 > num = 5 => 5 ruby-1.9.1-p378 > -num.to_s NoMethodError: undefined method `-@' for "5":String from (irb):5 from /Users/iain/.rvm/rubies/ruby-1.9.1-p378/bin/irb:17:in `
This also applies to the tilde method.
I don't know. Enrich your DSLs and APIs, if it makes any sense to do it.