Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 852
Kokizzu Avatar asked Oct 25 '13 10:10

Kokizzu


People also ask

How do you write if else in one line Ruby?

You can use:If @item. rigged is true, it will return 'Yes' else it will return 'No'.

How do you break out of if statements in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

What are conditional statements in Ruby?

Conditionals are formed using a combination of if statements and comparison and logical operators (<, >, <=, >=, ==, != , &&, ||) . They are basic logical structures that are defined with the reserved words if , else , elsif , and end .


2 Answers

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
like image 67
Sergio Tulentsev Avatar answered Oct 04 '22 01:10

Sergio Tulentsev


def something
  bla_permission_invalid || (
  # do something else
  true)
end
like image 26
tihom Avatar answered Oct 04 '22 00:10

tihom