I'm having unknown number of hashes. How to merge all those hashes into
single hash?
Thanks,
Buvana
--
Posted via http://www.ruby-forum.com/.
Think about the semantics here! What happens if the same key appears in
all the hashes? Which value takes priority?
You can use inject to merge the hashes, but you probably won't get the
desired result.
>
> Thanks,
> Buvana
Best,
--
Marnen Laibow-Koser
http://www.marnen.org
mar...@marnen.org
Sent from my iPhone
use "merge"... http://ruby-doc.org/core/classes/Hash.html#M002880
When you say you have "unknown number", are they in an array? if so,
iterate it an merge them...
@Marnen: If there is more than one key with same name, obviously it'll
be override. This is fine.
Anyway i'm trying to fetch the result separately. I'll reply with latest
updated soon.
Hash[*array_of_hashes.collect{|hash| hash.collect{|key,value|
[key,value].flatten}.flatten}.flatten]
=> {:first=>10, :second=>2, :third=>3}
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
>
>
> array_of_hashes = [{:first => 1, :second => 2}, {:first =>
> 10, :third => 3}]
>
> Hash[*array_of_hashes.collect{|hash| hash.collect{|key,value|
> [key,value].flatten}.flatten}.flatten]
> => {:first=>10, :second=>2, :third=>3}
Simpler, but same idea.
irb> Hash[*array_of_hashes.map{|_|_.to_a}.flatten]
=> {:second=>2, :third=>3, :first=>10}
-Rob
Rob Biedenharn
R...@AgileConsultingLLC.com http://AgileConsultingLLC.com/
r...@GaslightSoftware.com http://GaslightSoftware.com/
Actually, looks like you get the desired result
a = [{:first => 1, :second => 2}, {:first => 10, :third => 3}]
a.inject(:merge)
On Thu, Dec 9, 2010 at 9:18 AM, Marnen Laibow-Koser
<li...@ruby-forum.com> wrote:
> Priya Buvan wrote in post #967340:
>> Hi All,
>>
>> I'm having unknown number of hashes. How to merge all those hashes into
>> single hash?
>
> Think about the semantics here! What happens if the same key appears in
> all the hashes? Which value takes priority?
>
>
>>
>> Thanks,
>> Buvana
>
> Best,
> --
> Marnen Laibow-Koser
> http://www.marnen.org
> mar...@marnen.org
>
> Sent from my iPhone
>
> --
> Posted via http://www.ruby-forum.com/.
>