Arrays, symbols and association - looking for better idiom

Hi all,

I’m trying to associate non-symbol arguments with the most immediately
previous
symbol. The solution below works, but I suspect there’s an easier way:

def test(*args)
hash = {}
current = nil
args.each{ |arg|
if arg.is_a?(Symbol)
hash[arg] = []
current = arg
else
hash[current] << arg
end
}

hash

end

hash = test(:foo, 1, :bar, ‘a’, 7, :baz, /hello/, Fixnum)

p hash # {:foo=>[1], :bar=>[“a”, 7], :baz=>[/hello/, Fixnum]}

Any ideas? Some Array#assoc trick I’m missing?

Thanks,

Dan

This communication is the property of Qwest and may contain confidential
or
privileged information. Unauthorized use of this communication is
strictly
prohibited and may be unlawful. If you have received this communication
in error, please immediately notify the sender by reply e-mail and
destroy
all copies of the communication and any attachments.

On Jun 28, 2006, at 1:15 PM, Daniel B. wrote:

  if arg.is_a?(Symbol)

hash = test(:foo, 1, :bar, ‘a’, 7, :baz, /hello/, Fixnum)
This communication is the property of Qwest and may contain
confidential or
privileged information. Unauthorized use of this communication is
strictly prohibited and may be unlawful. If you have received this
communication in error, please immediately notify the sender by
reply e-mail and destroy all copies of the communication and any
attachments.

Well this isn’t any easier but it does use inject:

% cat ruby_hashbuild.rb
def test(*args)
args.inject([Hash.new{|h,k| h[k] = []}, nil]) do |(hash,
current_key), val|
case val
when Symbol
current_key = val
else
hash[current_key] << val
end
[hash, current_key]
end.first
end

hash = test(:foo, 1, :bar, ‘a’, 7, :baz, /hello/, Fixnum)
p hash

% ruby ruby_hashbuild.rb
{:bar=>[“a”, 7], :baz=>[/hello/, Fixnum], :foo=>[1]}