简体   繁体   中英

Populate a hash with an array of keys and a default value in Ruby

I have to write a method like so:

def populate_hash([key1, key2, key3], default_value)
  #
end

populate_hash([:apples, :oranges, :melons], 6) # { apples: 6, oranges: 6, melons: 6 }

If I was writing a method that was passing in two separate arrays (one for keys, one for values) it would be easy, but I'm unsure how to handle the default value.

Thank you.

Another way that might work is to use Array#product :

def populate_hash(array, default_value)
  Hash[array.product([default_value])]
end

If you are using Ruby 2.1+, you could use Array#to_h as well:

def populate_hash(array, default_value)
  array.product([default_value]).to_h
end

I believe the code is not much different from what you mention. Try this:

def populate_hash(a, default_value)
  result = {}
  a.each{|k| result[k] = default_value}
  return result
end

I have not added any checks to verify that a is and Array, but it is quite easy to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM