# I can take the returned arrays and transform them back into hashes,
# but it would be nice to avoid the extra step.
# Plus, it just surprised me that #select and #map aren't overridden for
# Hash to return new Hashes instead of arrays.
# Am I missing something?
i think this is an faq. in this regard, i'd like to request that the ruby faq be on the frontpage of ruby-lang.org and ruby-doc.org and that it be mirrored.
Hi Jeff.
My guess is because you need to enumerate over a Hash. Recall that entries
in a Hash are indexed by some Hashing algorithm, so it's kind of had to
enumerate over it's entries.
It's probably cheaper to toss all the entries in a Hash into an array and
iterate over it's index than to try and divine some means of iterating over
the non-sequential Hash table containing index values.
James
···
On 9/17/07, Jeff <cohen.jeff@gmail.com> wrote:
On Sep 17, 8:35 pm, franco <flazzar...@gmail.com> wrote:
> # use two vars in an map/select block (or use the index if one var)
> array = {:a => 1, :b =>2}.select {|k,v| k == :b}
> # => [[:b, 2]]
>
> # use inject to make a hash from a list, this is a great technique
> hash = array.inject({}) {|h,e| h.merge({e[0] => e[1]}) }
> # => {:b=>2}
>
> -franco
That was exactly my point - why doesn't Hash#select and Hash#map
return hashes instead of arrays?
On Sep 17, 11:45 pm, Peña, Botp <b...@delmonte-phil.com> wrote:
> From: Jeff [mailto:cohen.j...@gmail.com]
> just wait for 1.9http://eigenclass.org/hiki.rb?Changes+in+Ruby+1.9#l81
> why doesn't Hash#select and Hash#map
> return hashes instead of arrays?
My guess is because you need to enumerate over a Hash. Recall that entries
in a Hash are indexed by some Hashing algorithm, so it's kind of had to
enumerate over it's entries.
There's no problem enumerating over a Hash. Hash#each is implemented
after all. Enumerable only requires that each yield all of the
elements in SOME order, the fact that Hashes don't have a natural
ordering doesn't hamper this. Hash#each yields key,value pairs.
Ruby 1.9 is on track to change Hash#select to return a Hash.
Hash#map is problematic though, map returns a new enumeration which
contains the elements resulting in applying the block to each element
yielded by each. In general this could be anything for example:
{:a => "fred", :b => "barney"}.map { |k,v| "#{k} is associated
with #{v}" } # => ["a is associated with fred", "b is associated with
barney"]
···
On 9/18/07, James Herdman <james.herdman@gmail.com> wrote: