# Arrays, symbols and association - looking for better idiom

**URL:** <https://www.ruby-forum.com/t/arrays-symbols-and-association-looking-for-better-idiom/96435>\
**Category:** Ruby\
**Created:** [June 28, 2006, 7:44pm UTC](https://www.ruby-forum.com/t/arrays-symbols-and-association-looking-for-better-idiom/96435 "2006-06-28T19:44:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![danielb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c57346/32.png) [@danielb](https://www.ruby-forum.com/u/danielb)\
**Post date:** [June 28, 2006, 7:44pm UTC](https://www.ruby-forum.com/t/arrays-symbols-and-association-looking-for-better-idiom/96435/1 "2006-06-28T19:44:12Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![danielb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c57346/32.png) [@danielb](https://www.ruby-forum.com/u/danielb)\
**Post date:** [June 29, 2006, 7:26pm UTC](https://www.ruby-forum.com/t/arrays-symbols-and-association-looking-for-better-idiom/96435/2 "2006-06-29T19:26:48Z")

</div>

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]}
