Having received the Array from Return statement, output the string from this line

I have a conditional "Case" code snippet in which I return two objects. Pseudocode -

case name
when 'a'
object1 = - SQL Logic -
when 'b'
object1 = - SQL Logic -
when 'c'
object2 = - SQL Logic -
when 'd'
object2 = - SQL Logic - 
end
return object1, object2

      

As obvious, I am returning two objects. However, in my controller, I need one object at a time. The object is returned as an array, for example ['value', 'nil']. One of them is always zero. In my controller, I am passing one of these objects as -

Model.find_by_sql ["select * from #{object}"]  #either object1 or object2

      

Is there a way that I can disable this array and return the object that is required at that location as a String?

Thank.

+3


source to share


3 answers


return [object1, object2].compact



you can use the method compact

to remove the nil

array value .

0


source


While you can use compact

to exclude values nil

from your array, I'm not sure why you need this in the first place.

Performance



case name
  when 'a'
    return "SQL statement"
  when 'b'
    return "SQL statement"
  when 'c'
    return "SQL statement"
  when 'd'
    return "SQL statement"
end

      

is more intuitive.

+1


source


You can write:

return (['a', 'b'].include?(name) && - SQL Logic 1 -) ||
         (['c', 'd'].include?(name) && - SQL Logic 2 -)

      

If this is the last line of the method, you don't need to return

.

Let's see what happens.

If ['a', 'b'].include?(name) #=> true

, - SQL Logic 1 -

that is true, will be returned.

If ['a', 'b'].include?(name) #=> false

, the first sentence &&

is equal false

( - SQL Logic 1 -

not satisfied), so we will consider another sentence ||

. ['c', 'd'].include?(name)

must be true, so we return - SQL Logic 2 -

.

0


source







All Articles