Honestly, I've needed it many times and was surprised that it wasn't implemented yet. Of course, there are a few ways you can do this (probably more efficient way than what I suggested) but we also need to keep in mind that we should keep our code as DRY as possible.
On Monday, February 24, 2014 11:30:38 AM UTC-5, gautamrege wrote: > > Having an OrderedHash that saves insertion order is useful enough and I > personally don’t see a reason for a custom ordered hash. > Wouldn’t it be less expensive to order only the keys in a separate array > and access the hash rather than creating a new hash? > > My 2 cents. > -- > @gautamrege > ~~~~~~~~~~~~~~~ > All wiyht. Rho sritched mg kegtops awound? > > On 24-Feb-2014, at 8:58 pm, Artem Kalinchuk <[email protected]<javascript:>> > wrote: > > Would a custom order of a hash be useful in Rails? > > If I have the following Hash: > > my_hash = { key1: 'value', key2: 'value', key3: 'value' } > > > And I want to order it by the following keys: > > my_hash = my_hash.order(:key2, :key1, :key3) > > > I would get a new hash with the following result: > > puts my_hash > > => { key2: 'value', key1: 'value', key3: 'value' } > > > Using the following code: > > class Hash > def order(*keys) > Hash[keys.collect {|k| self[k] ? [k, self[k]] : nil }.compact] > end > end > > > Any thoughts? > > -- > You received this message because you are subscribed to the Google Groups > "Ruby on Rails: Talk" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected] <javascript:>. > To post to this group, send email to [email protected]<javascript:> > . > To view this discussion on the web visit > https://groups.google.com/d/msgid/rubyonrails-talk/285cec00-c279-405b-982e-0710501bcb68%40googlegroups.com > . > For more options, visit https://groups.google.com/groups/opt_out. > > > -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/ba8034af-bab6-4f4a-8771-41f1365c6e09%40googlegroups.com. For more options, visit https://groups.google.com/groups/opt_out.

