ther
1
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
ther
2
Hi —
-------- Original-Nachricht --------
Datum: Mon, 5 May 2008 22:10:31 +0900
Von: Damjan R. [email protected]
An: [email protected]
Betreff: Hash question
by
TheR
Posted via http://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
Best regards,
Axel
ther
3
2008/5/5 Axel E. [email protected]:
h = { “a” => 100, “b” => 200, “c” => 300 }
you can use Hash#select or Hash#delete or Hash#delete_if for tasks like
this.
See some examples in the documentation for Hash:
class Hash - RDoc Documentation
Unfortunately these return Array instead of Hash.
You can do something like this:
irb(main):006:0> ha = { “a” => 100, “b” => 200, “c” => 300 }
=> {“a”=>100, “b”=>200, “c”=>300}
irb(main):007:0> sel = %w{a c}
=> [“a”, “c”]
irb(main):008:0> ha.inject({}) {|h,(k,v)| h[k]=v if sel.include? k;h}
=> {“a”=>100, “c”=>300}
irb(main):012:0> Hash[*ha.select {|k,v| sel.include? k}.flatten]
=> {“a”=>100, “c”=>300}
Kind regards
robert
ther
4
On May 5, 8:42 am, “Robert K.” [email protected] wrote:
TheR
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.
ther
5
Dear Robert,
-------- Original-Nachricht --------
Datum: Mon, 5 May 2008 22:42:03 +0900
Von: “Robert K.” [email protected]
An: [email protected]
Betreff: Re: Hash question
Example:
Posted via http://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:
class Hash - RDoc Documentation
Unfortunately these return Array instead of Hash.
Hash#delete_if does indeed return a Hash (and I’m using ruby 1.8.6
(2007-06-07 patchlevel 36) [i486-linux]):
h = { “a” => 100, “b” => 200, “c” => 300 }
h.delete_if {|key, value| key >= “b” } #=> {“a”=>100}
So there’s no need to code yourself here.
But you’re right insofar as Hash#select returns a value and Hash@delete
returns an array.
Best regards,
Axel
ther
6
Here is what I have done:
class Hash
def select_as_hash(*args)
h = {}
args.each {|k| h[k]=self[k] unless self[k].nil? }
h
end
end
by
TheR