0

In Ruby my function func returns nil if myfunction1 returns a non nil value. I would somehow expect that func returns the value of rc. In other words it gets the value of the assignment even if it not executed:

def func
    rc = myfunction1
    rc = myfunction2 if rc.nil?
end

If I enhance func to this then func works like I expect:

def func
    rc = myfunction1
    rc = myfunction2 if rc.nil?
    rc
end

Here is simplified version to try it yourself:

def func
    rc = 3
    rc = myfunction2 if rc.nil?  # returns nil but rc has value 3
end

Is there is specific reason for this behaviour?

3 Answers 3

2

Let's step through your simplified example:

  1. You set rc to 3.
  2. In the next line, you check if rc is nil, which it obviously isn't.
  3. Hence the assignment will not be executed and since there is no else branch, the expression evaluates to nil.
  4. Since this is the last expression in the method, nil gets returned.

If you want to return rc in any case, you have to resort to your second form or write the entire method like this:

def func
  myfunction1 || myfunction2
end

This will obviously only work if false is not a possible return value of myfunction1. If it is, you can do this:

def func
  rc = myfunction1
  rc.nil? ? myfunction2 : rc
end
Sign up to request clarification or add additional context in comments.

Comments

0
if cond then expr end

returns nil if cond is false and the value of expr if cond is true.

if cond then expr_if else expr_else end

will return expr_else if cond is false.

This is why one can do (for instance)

value = if den != 0 then
         val / den
      else 0
      end

Comments

0

In your first definition of func, the last line has no definition for the else part of the if, so it is equivalent to:

if rc.nil? then
  rc = function2
else
  nil
end

You could use a guard clause to achieve your desired result:

def func
  rc = function1
  return rc unless rc.nil?
  function2
end

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.