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 [](*keys)
if keys.length == 1
fetch(keys.first, nil)
else
keys.map{|key| fetch(key, nil)}
end
end
end
Cheers,
Daniel
Daniel Schierbeck wrote:
class Hash
def (*keys)
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 (*keys)
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
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
···
On 6/11/06, Daniel Schierbeck <daniel.schierbeck@gmail.com> 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"]
Daniel Schierbeck wrote:
class Hash
def (*keys)
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 (*keys)
if keys.length == 1
fetch(keys.first) rescue default(keys.first)
else
keys.map{|key| fetch(key) rescue default(key)}
end
end
end
Daniel
shev
(shev)
11 June 2006 12:30
5
Seems not too bad. Or am I missing something?
···
--
Posted via http://www.ruby-forum.com/ .
Hash#values_at does what I want. Never mind.
!#%¤#!"%(§%§§"¤/"%/(!!!
Daniel