Daniel Schierbeck
8/14/2006 5:02:00 PM
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