Mar 22, 2007 @ 07:58 am

One of the little things that makes ruby so different is the fact that you can use punctuation in the name of your methods. I could really well be wrong on this, but I think ruby is the only language that allows a programmer to name his method logged? for example. Oh well, I should play it more safe. Let’s say that ruby is the only language I know that allow this.

It’s great because just by looking at the question mark, you know what the method is all about and that it will (should) return yes or no. The other punctuation character you can use is the exclamation (!). It is generally used to announce some kind of destructive action or something that is unusual. The “!” sign is used a lot in Rails ActiveRecord methods. For example, you can call both myObject.save and myObject.save!

What is the difference? myObject.save! will raise an exception if something went wrong in the process of saving the object back to the database while myObject.save will remain silent.

What’s your take on using punctuation in method names? Is it a useful feature or just flash in the pan?

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon
Rate this post :
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
Posted under : Easy reading
3 Comments
MyAvatars 0.2

unless user logged_in?

sounds pretty nice

Comment by : Peter
— March 29, 2007 @ 4:40 pm

MyAvatars 0.2

Thanks for that :)

So how do you do your own method like that?

For: ?
def method
return true or false
end

if method?
#do that
end

For: !

def method
raise “exception”
end

method!
rescue “exception”

or something like that?

Can you tell us how to use both ! or ? or nothing ?, a article/post about methods will be really great :D

Comment by : Jamal Soueidan
— March 30, 2007 @ 7:51 pm

MyAvatars 0.2

Hey Jamal,

The “?” and “!” characters are not doing something special on their own. It’s just that you can include them in the name of your methods if you want. It’s only a convention to use the “?” character in methods that does nothing worth of mention other than returning yes or no. As it’s just a convention to use the “!” character in methods that do something destructive or “dangerous”. You could (but should not) use them for other purpose.

So, if you want to write : if my_method? …

You would have to define it this way :

def my_method?
return true #or false, or anything you want
end

If you want to write : destroy!

You would have to define it this way :

def destroy!
#Do something destructive like deleting all rows of a table in a DB
end

I hope it does answer your question

Comment by : Frank
— March 31, 2007 @ 9:12 am




Leave a comment
Name (required)
Email (will not be publish) (required)
Website