# Ruby method return values - how to be more Ruby-like?

How should I make this more Ruby-like or just "better"?

def password_format_is_valid?(submitted_password)

#Gets regular expression for password format validation from settings and applies it
if submitted_password =~ regex then
return true
else
return false
end

end

-

It seems like you need a Rails validation callback (and a virtual attribute for submitted_password). I'd write:

attr_accessor :submitted_password

unless submitted_password =~ regex
false
end
end


• In the vein of Lisp, the last expression of a body in Ruby is the return value of the method/block, so no need to use an explicit return (in fact it's unidiomatic and discouraged)

• Note that Rails can validate fields with regular expression, you should use the predefined validations whenever possible: validates_format_of.

-
Thank you for the explanation and example - much appreciated! –  Douglas Birch Oct 10 '12 at 15:03
This returns nil when the password is valid. –  steenslag Nov 10 '12 at 21:09
@steenslag: Indeed, I tried to write the method as a Rails callback, but the code was incomplete. Edited. –  tokland Nov 10 '12 at 21:42
Care to expand your answer a bit to explain why return can be omitted? –  Yannis Oct 10 '12 at 4:30