Adventures with Ruby

Odd Ruby Methods

View Comments

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 sense.

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.

So?

I don’t know. Enrich your DSLs and APIs, if it makes any sense to do it.

Written by Iain Hecker

March 30th, 2010 at 9:37 am

Posted in iain.nl

  • http://topsy.com/trackback?utm_source=pingback&utm_campaign=L2&url=http://iain.nl/2010/03/odd-ruby-methods/ Tweets die vermelden iain.nl » Odd Ruby Methods — Topsy.com

    [...] Dit blogartikel was vermeld op Twitter door Iain, Ruby Reflector. Ruby Reflector heeft gezegd: Top Ruby Article: Odd Ruby Methods: http://bit.ly/bFIwCt [...]

  • http://www.ubervu.com/conversations/iain.nl/2010/03/odd-ruby-methods/ uberVU – social comments

    Social comments and analytics for this post…

    This post was mentioned on Twitter by iain_nl: New post: Odd Ruby Methods (http://iain.nl/2010/03/odd-ruby-methods/) http://iain.nl/2010/03/odd-ruby-methods/...

blog comments powered by Disqus
Fork me on GitHub