Ruby single line if return statement

Is there a way to shorten this line in Ruby?

if (res = bla_permission_invalid).is_a? String then return res end 

about

 def something # many things that like this if (res = bla_permission_invalid).is_a? String then return res end # do something else return true end 

when the contents of bla_permission_invalid look like

 def bla_permission_invalid return invalid_address_report_func if invalid_address? return permission_error_report_func if @user.not_one_of? [ :group1, :group2 ] return nil end 

invalid_adress_report_func and permission_error_report_func returns a string

+8
ruby return refactoring
source share
4 answers

If the possible values ​​are String and NilClass , then the code can be simplified to this:

 def something res = bla_permission_invalid() return res if res # strings are truthy, so they'll be returned but nil will proceed # do something else true end 
+4
source share
 def something bla_permission_invalid || ( # do something else true) end 
+5
source share

For fun, you can rewrite your something method as follows:

 def something true.tap do bla_permission_invalid.tap { |res| return res if res.is_a? String } # do something else (thx Sergio) end end 

But more importantly, Mark Thomas deserves recognition for his observation that the problem should be resolved using custom exceptions.

The error code approach is good in languages ​​that have no exceptions. Ruby has them.

+2
source share
Mark Thomas already noted in his comment that it looks like you are trying to handle errors yourself using some kind of string identifier. You can use exceptions instead:
 class AddressError < StandardError; end class PermissionError < StandardError; end def something bla_permission_invalid # do something true end def bla_permission_invalid raise AddressError if invalid_address? raise PermissionError if @user.not_one_of? [ :group1, :group2 ] end 

In the above code, something calls bla_permission_invalid , does its job, and returns true . If an exception occurs in bla_permission_invalid , it automatically extends to the call stack, you do not need to explicitly return it from something .

To handle the exception:

 begin something rescue AddressError # handle address error rescue PermissionError # handle permission error end 
+1
source share

All Articles