Project

General

Profile

Feature #6079

Hash#each_sorted

Added by walker (Walter Urbaniak) over 7 years ago. Updated over 7 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:42870]

Description

I often use my own mixin'd Hash#each_sorted that sorts the hash keys and then calls the block with the key and value. It would be useful to be added to Hash. (If this is already in Hash or Enumerable, I didn't see it.)

class Hash
def each_sorted(&block) # sort by key
self.keys.sort.each {|key| block.call(key, self[key])}
end
end

History

Updated by marcandre (Marc-Andre Lafortune) over 7 years ago

I feel there is no need for each_sorted as it is equivalent to sort.each (and 2 characters longer). Try:

{1 => 2, 0 => 4}.sort.each{|k, v| p "#{k} => #{v}"}

Updated by mame (Yusuke Endoh) over 7 years ago

Hello,

2012/2/25 Marc-Andre Lafortune ruby-core@marc-andre.ca:

I feel there is no need for each_sorted as it is equivalent to sort.each (and 2 characters longer).

Agreed. If we can implement the feature without creating an
intermediate array, it might be useful. But I have no idea
to implement.

--
Yusuke Endoh mame@tsg.ne.jp

Updated by trans (Thomas Sawyer) over 7 years ago

=begin
{1 => 2, 0 => 4}.lazy.sort.each{|k, v| p "#{k} => #{v}"}
=end

?

Updated by nobu (Nobuyoshi Nakada) over 7 years ago

Hi,

(12/02/25 9:24), Yusuke Endoh wrote:

Agreed. If we can implement the feature without creating an
intermediate array, it might be useful. But I have no idea
to implement.

It would be possible, if you can tell if the current item is smaller
than the next item before fetching the latter. In other words, it'll
need a time machine.

--
Nobu Nakada

Updated by marcandre (Marc-Andre Lafortune) over 7 years ago

  • Status changed from Open to Rejected

Closing as no implementation can improve on simple sort.each.

Also available in: Atom PDF