3

I have a 'Case' conditional code snippet wherein I am returning two objects. The psuedocode is -

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 evident, I am returning two objects. However, in my Controller I need one object at a time. The object are returned in form of Array like ['value', 'nil']. One of them is always nil. In my controller I am passing one of these objects as -

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

Is there any way that I can break off this array and return the object that is required at that place as String?

Thanks.

3 Answers 3

1

While you can use compact to eliminate the nil values from your array, I'm not sure why you need this in the first place.

Doing

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

is way more intuitive.

Sign up to request clarification or add additional context in comments.

4 Comments

Can u also explain to me why if I am trying to access one of the returned object, let's say object1 , it single-handedly behaves as an array. like, object1 - ['value', nil] ?
It behaves like an array because you return an array. When you return two values, they get put into a single one, an array.
case, not "Case". (Always test!) Consider case name; when 'a','b','c','d' then return "SQL statement"; end or return "SQL statement" if ['a','b','c','d'].include?(name). –
yes thanks for pointing it out..that was actually a Typo..have corrected it now. @CarySwoveland
0

return [object1, object2].compact

you can use compact method to remove nil value of array.

Comments

0

You could write:

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

If it's the last line of a method, you don't need return.

Let's see what's happening.

If ['a', 'b'].include?(name) #=> true, - SQL Logic 1 -, which is truthy, will be returned.

If ['a', 'b'].include?(name) #=> false, the first && clause is false (- SQL Logic 1 - is not executed), so we consider the other || clause. ['c', 'd'].include?(name) must be true, so we return - SQL Logic 2 -.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.