Multiple assignment in a hash

K

Kevin Olbrich

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
 
L

Logan Capaldo

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
 
R

Robin Stocker

Logan said:
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
 
L

Logan Capaldo

Logan said:
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.
 
D

Daniel Schierbeck

Kevin said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,209
Messages
2,571,088
Members
47,687
Latest member
IngridXxj

Latest Threads

Top