Multiple assignment in a hash

Anyone know of any ruby shortcuts for multiply assigning elements in a hash?

What I need to do is set up a hash like this...

{ "one" => "A", "two"=>"A", "three" => "A" }

What I would like to do is something like this....

{ "one","two","three" => "A" } (this doesn't work)

_Kevin
www.sciwerks.com

···

--
Posted with http://DevLists.com. Sign up and save your mailbox.

Anyone know of any ruby shortcuts for multiply assigning elements in a hash?

What I need to do is set up a hash like this...

{ "one" => "A", "two"=>"A", "three" => "A" }

What I would like to do is something like this....

{ "one","two","three" => "A" } (this doesn't work)

keys = %w(one two three)
hash = Hash[ *keys.zip(Array.new(keys.length){"A"}).flatten ]

Or maybe in this case the default is good enough?

hash = Hash.new { |h,k| h[k] = "A" }
hash.values_at("one", "two", "three")
p hash

···

On Aug 13, 2006, at 10:43 PM, Kevin Olbrich wrote:

_Kevin
www.sciwerks.com
--
Posted with http://DevLists.com. Sign up and save your mailbox.

Kevin Olbrich wrote:

Anyone know of any ruby shortcuts for multiply assigning elements in a hash?

What I need to do is set up a hash like this...

{ "one" => "A", "two"=>"A", "three" => "A" }

What I would like to do is something like this....

{ "one","two","three" => "A" } (this doesn't work)

Perhaps this?

   class Hash
     def = (*keys)
       value = keys.pop
       keys.each{|key| store(key, value) }
     end
   end

   hsh = {}
   hsh[:a, :b, :c] = 42
   hsh #=> {:a => 42, :b => 42, :c => 42}

Do remember that all keys will have the *same* value, so:

   hsh[:a, :b] = "foo"
   hsh[:a].upcase!
   hsh[:b] #=> "FOO"

Cheers,
Daniel

Logan Capaldo wrote:

keys = %w(one two three)
hash = Hash[ *keys.zip(Array.new(keys.length){"A"}).flatten ]

Why complicated when you could do it easier and clearer:

hash = {}
%w(one two three).each{ |k| hash[k] = "A" }

   Robin

I dunno. Didn't think of it at the time.

···

On Aug 14, 2006, at 7:47 AM, Robin Stocker wrote:

Logan Capaldo wrote:

keys = %w(one two three)
hash = Hash[ *keys.zip(Array.new(keys.length){"A"}).flatten ]

Why complicated when you could do it easier and clearer:

hash = {}
%w(one two three).each{ |k| hash[k] = "A" }

  Robin