Sunday, 8 September 2013

Why are these two methods that seem the same operate differently?

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 "exist­s_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 exist­s_else(true, false) should return true. In my first
implementation, shown below, it returns false.
> true.nil?
=> false
> def exist­s_else(base, fallback)
base unles­s base.nil­? else fallback
end
=> nil
> a = true
=> true
> exists_els­e( 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 exist­s_else(bas­e, fallb­ack)
unless base.­nil?
base
else
fallb­ack
end
end
=> nil
> a = true
=> true
> exists_els­e( a, false­ )
=> true

No comments:

Post a Comment