turning array into hash

45 views
Skip to first unread message

doron

unread,
Apr 9, 2008, 9:38:55 AM4/9/08
to Israel.rb
Is there an internal ruby method or an acceptable pattern to turn an
array into an hash?
I generally want the array values to be the keys and the value to be
true.

i thought of something like this:

def array_to_hash(a)
hash = Hash.new
a.each do |a_value|
hash[a_value] = true
end
hash
end

i guess it can also receive a block to determine the value ...

doron

unread,
Apr 9, 2008, 9:51:12 AM4/9/08
to Israel.rb
maybe something like this:
def array_to_hash(a)
hash = Hash.new
a.each do |a_value|
key, value = yield(a_value)
hash[key] = value
end
hash
end


?

Evgeny

unread,
Apr 9, 2008, 9:59:38 AM4/9/08
to isra...@googlegroups.com
First version was okay ... what you need the yield for ???

Boris Nadion

unread,
Apr 9, 2008, 10:01:46 AM4/9/08
to isra...@googlegroups.com
a = [1, 2, 3, 'other']
h = a.inject({}) {|h, v| h[v] = true; h }

h will be {1 => true, 2 => true, 3 => true, 'other' => true}

On Wed, Apr 9, 2008 at 4:51 PM, doron <doron...@gmail.com> wrote:
>

--
Boris Nadion

doron

unread,
Apr 9, 2008, 10:46:47 AM4/9/08
to Israel.rb
i should have explained.
i thought about something more general, the method will receive a
block that for each array element deceide what should be the key and
what should be the value,
so that if elements are objects the caller will know the object's
schema, but the array_to_hash method doesn't need to know about it.

On Apr 9, 4:59 pm, Evgeny <evgeny.zis...@gmail.com> wrote:
> First version was okay ... what you need the yield for ???
>

Boris Nadion

unread,
Apr 9, 2008, 3:17:59 PM4/9/08
to isra...@googlegroups.com
anyway: using inject is the general pattern

--
Boris Nadion

Vitaly Kushner

unread,
Apr 9, 2008, 8:28:46 PM4/9/08
to Israel.rb
Don't forget the Hash[....] form to create the hash:

>> Hash[1,2,3,4]
=> {1=>2, 3=>4}

It doesn't help for your situation, but sometimes its quite helpful.

taa...@gmail.com

unread,
Apr 11, 2008, 6:17:33 PM4/11/08
to Israel.rb
There is a Rails extension to Enumerable called index_by, it looks
that it does exactly what you need.

The implementation of this method is:

# File vendor/rails/activesupport/lib/active_support/core_ext/
enumerable.rb, line 56
def index_by
inject({}) do |accum, elem|
accum[yield(elem)] = elem
accum
end
end
Reply all
Reply to author
Forward
0 new messages