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

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

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

Logan C. 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

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

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

Kevin O. 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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs