Hash#select, different than documented?

J

Jonathan Rochkind

The documentation at:
http://www.ruby-doc.org/core/classes/Hash.html#M000750

Says that Hash#select does this:

Returns a new hash consisting of entries for which the block returns
true.

If no block is given, an enumerator is returned instead.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
h.select {|k,v| v < 200} #=> {"a" => 100}

***

However, that is not the behavior I am seeing in my ruby 1.8.6. Is that
documentation for a later version of ruby, in which this behavior
changed? Or is the documentation just wrong?

I instead get an array of pairs returned. From irb:

irb(main):008:0> h = { "a" => 100, "b" => 200, "c" => 300 }
=> {"a"=>100, "b"=>200, "c"=>300}
irb(main):009:0> h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
=> [["b", 200], ["c", 300]]
irb(main):010:0> h.select {|k,v| v < 200} #=> {"a" => 100}
=> [["a", 100]]



Is there any other search behavior implemented on Hash I could be using
instead, with more convenient behavior for finding hash subsets, and/or
finding hash keys whose values are matched by a certain block?
 
A

Anurag Priyam

However, that is not the behavior I am seeing in my ruby 1.8.6. =A0Is tha=
t
documentation for a later version of ruby, in which this behavior
changed? Or is the documentation just wrong?

I remember a mail on the list by James Britt stating that ruby-doc.org
has been updated for 1.9 to be the default. I can confirm the expected
behavior (returning a Hash) on 1.9.2 and 1.8.7.
Is there any other search behavior implemented on Hash I could be using
instead, with more convenient behavior for finding hash subsets, and/or
finding hash keys whose values are matched by a certain block?

Passing the return value of select to Hash.[] method might help your case.
h =3D { "a" =3D> 100, "b" =3D> 200, "c" =3D> 300 }
Hash[h.select {|k,v| k > "a"}] #=3D> {"b" =3D> 200, "c" =3D> 300}

--=20
Anurag Priyam
http://about.me/yeban/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top