Thursday, 22 August 2013

How to check if an array/hash key exists before calling it?

How to check if an array/hash key exists before calling it?

I want to print the value of an array/hash key without raising exception
when the index is not found. (note I'm not looking for rescue here)
<%= content.categories[0].name %>
In the above statement, if categories is an empty array, it will throw an
exception. Since I'm using this code in my views, I want a code that is
very brief and yet prints nothing if categories is empty.

No comments:

Post a Comment