From: Yossef Mendelssohn Date: 2008-05-06T00:14:33+09:00 Subject: Re: Hash question On May 5, 8:42 am, "Robert Klemme" wrote: > 2008/5/5 Axel Etzold : > > > > > Hi --- > > -------- Original-Nachricht -------- > > > Datum: Mon, 5 May 2008 22:10:31 +0900 > > > Von: Damjan Rems > > > An: ruby-t...@ruby-lang.org > > > Betreff: Hash question > > > > I would like to return only part of hash as hash object. > > > > Example: > > > h = { "a" => 100, "b" => 200, "c" => 300 } > > > result = h.somemethod('a','c') > > > # should result in { "a" => 100, "c" => 200} > > > > Is this already build in Hash object or should I start and code it. > > > > by > > > TheR > > > -- > > > Posted viahttp://www.ruby-forum.com/. > > > you can use Hash#select or Hash#delete or Hash#delete_if for tasks like > > this. > > See some examples in the documentation for Hash: > > > http://www.ruby-doc.org/core/classes/Hash.html#M002898 > > Unfortunately these return Array instead of Hash. > > Kind regards > > robert > > -- > use.inject do |as, often| as.you_can - without end Fortunately, this bone-headed behavior will be fixed in 1.9. Until then, you can do what many others do and use Hash#reject with negative logic. In other words, instead of { "a" => 100, "b" => 200, "c" => 300 }.select { |k, v| %w[a c].include?(k) } use { "a" => 100, "b" => 200, "c" => 300 }.reject { |k, v| !%w[a c].include?(k) } Yes, I like this about as much as you'd think. -- -yossef