tags:

views:

64

answers:

5

Is the keyword unless the same as if?

When do you use ??

I've seen:

if someobject?

I know it checks against nil correct?

+5  A: 

Is the keyword 'unless' the same as 'if' ?

No, it's the opposite.

unless foo is the same as if !foo

if someobject?

I know it checks against nil correct?

No it calls a method named someobject?. I.e. the ? is just part of the method name.

? can be used in methodnames, but only as the last character. Conventionally it is used to name methods which return a boolean value (i.e. either true or false).

? can also be used as part of the conditional operator condition ? then_part : else_part, but that's not how it is used in your example.

sepp2k
A: 

unless is actually the opposite of if. unless condition is equivalent to if !condition.

Which one you use depends on what feels more natural to the intention you're expressing in code.

e.g.

unless file_exists?
  # create file
end

vs.

if !file_exists?
  # create file
end

Regarding ?, there is a convention for boolean methods in Ruby to end with a ?.

mikej
+1  A: 

I think the convention for ?-suffix is to use it when naming a method that returns a boolean value. It is not a special character, but is used to make the name of the method easier to understand, or at least I think that's what the intention was. It's to make it clear that the method is like asking a question: it shouldn't change anything, only return some kind of status...

There's also !-suffix that I think by convention means that the method may have side-effects or may modify the object it is called on (rather than return a modified copy). Either way, the ! is to make you think carefully about calling such a method and to make sure you understand what that method does.

I don't think anything enforces these conventions (I've never tried to break them) so of course you could abuse them horribly, but your fellow developers would not be happy working with your code.

for unless see here: http://railstips.org/blog/archives/2008/12/01/unless-the-abused-ruby-conditional/

FrustratedWithFormsDesigner
+2  A: 

This statement:

unless conditional expression

Is the equivalent to:

if not (conditional expression)

In Ruby you can end your method names with a question mark which is normally used to show that it is a boolean method. With Rails a check against nil would look like this:

someobject.nil?

This calls the nil?() method of the object, which returns true for NilObject and false for anything else.

robbrit
A: 
if someobject?

The appending of a '?' here only means that it returns a boolean.

willcodejavaforfood