Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate hash with array keys and default value

Tags:

ruby

hash

Stuck on a Code Wars Challenge: Complete the solution so that it takes an array of keys and a default value and returns a hash with all keys set to the default value.

My answer results in a parse error:

def solution([:keys, :default_value])
  return { :keys => " ", :default_value => " " }
end

Am I missing something to do with returning a hash key with all the keys set to the default value?

like image 943
HandDisco Avatar asked Jan 12 '14 11:01

HandDisco


2 Answers

Do as below :

def solution(keys,default_val)
  Hash[keys.product([default_val])]
end

solution([:key1,:key2],12)  # => {:key1=>12, :key2=>12}

Read Array#product and Kernel#Hash.

like image 85
Arup Rakshit Avatar answered Oct 23 '22 07:10

Arup Rakshit


I'd advise amending your solution to this:

def solution(keys, default_value)
  hash = {}
  keys.each do |key|
    value = default_value.dup rescue default_value
    hash[key] = value
  end
  hash
end

The dup is to work around the nasty case where default_value is a string and you then do e.g.:

hash[:foo] << 'bar'

… with your version, this would modify multiple values in place instead of a single one.

like image 20
Denis de Bernardy Avatar answered Oct 23 '22 05:10

Denis de Bernardy