Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing durations as hash keys in Rails
    text
    copied!<p>Since I'm dealing quite a lot with durations in my Rails app, I would also like to use them as hash keys in some places. However, it does not seem to work as expected for me.</p> <p>Creating the initial hash works fine. For example, the following will work:</p> <pre><code>&gt;&gt; hash = {1.week =&gt; 'abc', 1.month =&gt; 'def'} </code></pre> <p>However, retrieving the values from the hash is not possible:</p> <pre><code>&gt;&gt; hash[1.month] =&gt; nil </code></pre> <p>Some further investigation showed me the reason for this:</p> <pre><code>&gt;&gt; 1.week.eql? 1.week =&gt; false </code></pre> <p>Which was quite unexpected</p> <p>Furthermore, it seems like these objects behave differently to normal objects of FixNum class. For normal FixNum objects, the value of the object_id seems to be always the same, e.g:</p> <pre><code>&gt;&gt; 15.object_id =&gt; 31 &gt;&gt; 15.object_id =&gt; 31 </code></pre> <p>For Durations, this is different, although they are from the same class</p> <pre><code>&gt;&gt; 1.month.class =&gt; Fixnum &gt;&gt; 1.month.object_id =&gt; 70305513092140 &gt;&gt; 1.month.object_id =&gt; 70305513086860 </code></pre> <p>So, it seems like the objects are always different, which is why hashes will not work. The only solution is to access with exactly the same object:</p> <pre><code>&gt;&gt; a = 1.month =&gt; 1 month &gt;&gt; hash = {a =&gt; 'b'} =&gt; {1 month=&gt;"b"} &gt;&gt; hash[a] =&gt; "b" </code></pre> <p>Obviously, this is not always possible if you have a lot of objects with dynamically created durations.</p> <p>Grouping by durations does not work either:</p> <pre><code>&gt;&gt; limits.group_by(&amp;:duration) =&gt; #&lt;OrderedHash {1 month=&gt;[#&lt;Limit:0x7fe28e441380&gt;], 1 month=&gt;[#&lt;Limit:0x7fe28e4290c8&gt;]}&gt; </code></pre> <p>So, I'm wondering whether it is possible to get durations working as hash keys somehow? So far I have not found a good solution and I'm not sure if there is one. The important this is that functions like (Time.now - duration) should keep working.</p> <p>FYI: My Ruby version - 1.8.7, Rails version - 2.3.18</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload