× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Ruby Hash and Array type coercion to avoid nil-checks

Yitz Schaffer
Jun 17, 2015
<p>Are you doing Array, Hash, or String operations with objects that might be <code>nil</code>? Don't let nil-checks clutter your beautiful code!</p> <p>Ruby provides coercion to sanitize possible <code>nil</code> values.</p> <p>If the object passed in is already a Hash or Array, the same object is returned; otherwise, an empty object is returned.</p> <p>For Arrays, the type coercion will also convert scalar values to an Array containing the scalar.</p> <p>For Strings, the type coercion will convert a nil to an empty string.</p> <h2>Hash</h2> <pre>&gt; our_hash = {foo: 'bar'} =&gt; {:foo=&gt;"bar"} &gt; Hash(our_hash) =&gt; {:foo=&gt;"bar"} &gt; Hash(nil) =&gt; {}​ &gt; Hash(our_hash).object_id == our_hash.object_id =&gt; true </pre> <h2>Array</h2> <pre>&gt; our_array = [1, 2, 3] =&gt; [1, 2, 3] &gt; our_scalar = 1 =&gt; 1 &gt; Array(our_array) =&gt; [1, 2, 3] &gt; Array(our_scalar) =&gt; [1] &gt; Array(nil) =&gt; [] &gt; Array(our_array).object_id == our_array.object_id =&gt; true </pre> <h2>String</h2> <pre>&gt; String("hello") =&gt; "hello" &gt; String(nil) =&gt; "" </pre>
comments powered by Disqus