Hash#[]

Am I the only one who thinks this would be a natural behavior for
Hash#[]?

hsh = {:foo => ‘FOO’, :bar => ‘BAR’, :baz => ‘BAZ’}
hsh[:foo] #=> “FOO”
hsh[:foo, :baz] #=> [“FOO”, “BAZ”]

That would enable us to do the following

def initialize(opts = {})
@host, @user, @pass = opts[:host, :user, :pass]
end

Since the old functionality isn’t changed, it would be backwards
compatible.

Implementation:

class Hash
def
if keys.length == 1
fetch(keys.first, nil)
else
keys.map{|key| fetch(key, nil)}
end
end
end

Cheers,
Daniel

Daniel S. wrote:

class Hash
def
if keys.length == 1
fetch(keys.first, nil)
else
keys.map{|key| fetch(key, nil)}
end
end
end

The implementation needs a little update:

class Hash
def
if keys.length == 1
fetch(keys.first, default(keys.first))
else
keys.map{|key| fetch(key, default(key))}
end
end
end

That should take care of default values and such.

Daniel

Daniel S. wrote:

class Hash
def
if keys.length == 1
fetch(keys.first, default(keys.first))
else
keys.map{|key| fetch(key, default(key))}
end
end
end

This was much simpler in my head…

class Hash
def
if keys.length == 1
fetch(keys.first) rescue default(keys.first)
else
keys.map{|key| fetch(key) rescue default(key)}
end
end
end

Daniel

Hash#values_at does what I want. Never mind.

!#%¤#!"%(§%§§“¤/”%/(!!!

Daniel

Seems not too bad. Or am I missing something?

On 6/11/06, Daniel S. [email protected] wrote:

Am I the only one who thinks this would be a natural behavior for Hash#[]?

hsh = {:foo => ‘FOO’, :bar => ‘BAR’, :baz => ‘BAZ’}
hsh[:foo] #=> “FOO”
hsh[:foo, :baz] #=> [“FOO”, “BAZ”]

No, you’re not. However, there is Hash#values_at() which already does
the same thing.
(Can anyone remind me why Hash#[] doesn’t allow *args?)

Regards,
Sean