# Strange logic problem

**URL:** <https://www.ruby-forum.com/t/strange-logic-problem/88226>\
**Category:** Rails\
**Created:** [March 9, 2007, 12:36am UTC](https://www.ruby-forum.com/t/strange-logic-problem/88226 "2007-03-09T00:36:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![edlitmus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/e495f1/32.png) [@edlitmus](https://www.ruby-forum.com/u/edlitmus)\
**Post date:** [March 9, 2007, 12:36am UTC](https://www.ruby-forum.com/t/strange-logic-problem/88226/1 "2007-03-09T00:36:33Z")

</div>

Hi all,

I have a template that is sometimes given a local like so:

render :partial =\> ‘shared/new\_addresses’, :locals =\> {:addresses =\>  
addresses}

In the partial I do this to make sure everything is cool:

if defined? addresses && !addresses.nil? && addresses[:z\_address]  
@address = addresses[:z\_address]  
end

Now, here’s where things get weird. After the app has been running a  
while in production I start getting exceptions being thrown due to  
addresses being nil on the assignment line above. Even though I make  
sure it isn’t in the if statement!

If I do this:

if defined? addresses && !addresses.nil? && addresses[:z\_address]  
if !addresses.nil?  
@address = addresses[:z\_address]  
end  
end

I don’t get the errors.

Any one have a clue as to what is happening here?

Cheers,

–Ed

---

<div class="post-metadata">

**Author:** ![edlitmus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/e495f1/32.png) [@edlitmus](https://www.ruby-forum.com/u/edlitmus)\
**Post date:** [March 9, 2007, 1:07am UTC](https://www.ruby-forum.com/t/strange-logic-problem/88226/2 "2007-03-09T01:07:36Z")

</div>

> render :partial =\> ‘shared/new\_addresses’, :locals =\> {:addresses =\>  
> addresses}
> 
> In the partial I do this to make sure everything is cool:
> 
> if defined? addresses && !addresses.nil? && addresses[:z\_address]  
> @address = addresses[:z\_address]  
> end

defined? will not work as expected with variables passed as locals to a  
partial. You should use instead  
local\_assigns.has\_key? addresses

You could also work aroud that by doing  
addresses ||= nil

That way if it was undefined initially, it will be nil after that, so  
you can check it with addresses.nil? directly

regards,

javier ramirez

## –

Estamos de estreno… si necesitas llevar el control de tus gastos  
visita [http://www.gastosgem.com](http://www.gastosgem.com) !!Es gratis!!

---

<div class="post-metadata">

**Author:** ![edlitmus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/e495f1/32.png) [@edlitmus](https://www.ruby-forum.com/u/edlitmus)\
**Post date:** [March 9, 2007, 4:25pm UTC](https://www.ruby-forum.com/t/strange-logic-problem/88226/3 "2007-03-09T16:25:38Z")

</div>

Thanks Javier! Using local\_assigns.has\_key? does the trick.

Cheers,

–Ed
