Kokizzu
Kokizzu

Reputation: 26838

Ruby one line if return statement

is there a way to shorten this line on Ruby?

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

on

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 content of bla_permission_invalid are something 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 string

Upvotes: 8

Views: 14241

Answers (4)

Stefan
Stefan

Reputation: 114178

Mark Thomas already noted in his comment that it looks like you're trying to handle errors on your own using some kind of string identifier. You could 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, performs its work and returns true. If an exception is raised in bla_permission_invalid, it automatically propagates up the call stack, you don't have to explicitly return it from something.

To handle the exception:

begin
  something
rescue AddressError
  # handle address error
rescue PermissionError
  # handle permission error
end

Upvotes: 1

tihom
tihom

Reputation: 8003

def something
  bla_permission_invalid || (
  # do something else
  true)
end

Upvotes: 5

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

For fun, one could rewrite your something method like this:

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 credit for his observation, that the problem at hand should be solved by using custom exceptions.

Error code approach is good in languages that don't have exceptions. Ruby has them.

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

If 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

Upvotes: 7

Related Questions