Why are these two methods that seem the same operate differently?
I finally got some code to work, but not sure why it works this way.
What I was trying to do was use a helper method "exists_else". The
function takes two parameters - a base, and a fallback. If the base is
nil, return the fallback. If its not nil, return the base.
A call to exists_else(true, false) should return true. In my first
implementation, shown below, it returns false.
> true.nil?
=> false
> def exists_else(base, fallback)
base unless base.nil? else fallback
end
=> nil
> a = true
=> true
> exists_else( a, false )
=> false
However, if I change the exists_else method to use a more standard looking
if-statement rather than the inline one, true is returned like I thought
it would be.
> def exists_else(base, fallback)
unless base.nil?
base
else
fallback
end
end
=> nil
> a = true
=> true
> exists_else( a, false )
=> true
No comments:
Post a Comment