About the present method in rails, how to use?

Hi, guys

I read this book ‘Agile web development with rails’ and know this
present, so i have some question.
How to use this present method?
What is the usage of this method ?
Can you give me a example for explaining it?

Thanks a lot.


First, be careful, the name of the method is actually “present?”, with
the ‘?’. There is another method called “blank?”, what this last
method does is asking if an object (or variable) is, let’s say, in a
‘black state’, that is whether it is nil, empty or an empty string and
returns true. So you would do things like:

book = “”

if book.blank?
book = writer.write_book

We are asking if the book has something written on it, and if it
doesn’t, we write something on it, otherwise, just read it. As you can
see, book is “” which is an empty string, so something will be written

If you go and check the source code
(present? (Object) - APIdock) of “present?”, you will
find this :

def present?

From this we can say that an object will return true if it is NOT
blank. To summarize, “present?” checks if an object is nil, or empty,
or “” and returns false if the object is in fact in one of the
previous states, otherwise it returns true.

So we could rewrite the previous example as

if book.present?
book = writer.write_book

Hope this helps!

Many thanks to Alejandro, that is very helpful.

2011/8/7 Alejandro C. [email protected]