Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips on understanding Ruby syntax, when to use ?, and unless

Tags:

ruby

Is the keyword unless the same as if?

When do you use ??

I've seen:

if someobject?

I know it checks against nil correct?

like image 868
Blankman Avatar asked Dec 02 '22 04:12

Blankman


2 Answers

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.

like image 112
sepp2k Avatar answered Dec 09 '22 22:12

sepp2k


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

like image 23
mikej Avatar answered Dec 09 '22 21:12

mikej