在Ruby中动态构造哈希

时间:2018-02-06 10:48:40

标签: ruby

我有以下ruby代码,它创建一个具有指定格式的哈希:

  result.each do |result|
    if domain == 'social'
      hash[result['date']] = {
        'positive' => result['positive'],
        'negative' => result['negative'],
        'declined' => result['declined']
      }
    end

    if domain == 'motivation'
      hash[result['date']] = {
        'high'   => result['high'],
        'medium' => result['medium'],
        'low'    => result['low']
      }
    end
  end

有没有办法删除这些重复并以更干净的方式执行此操作?

3 个答案:

答案 0 :(得分:1)

您可以使用Hash#select

social_keys = ['positive', 'negative', 'declined']
hash[result['date']] = result.select {|k, _| social_keys.include? k }

答案 1 :(得分:1)

根据域值,可能会为hash[result['date']]创建哈希值?:

result.each do |result|
  keys = case domain
         when 'social' then %w[positive negative declined]
         when 'motivation' then %w[high medium low]
         end
  hash[result['date']] = keys.each_with_object(Hash.new(0)) { |e, h| h[e] = result[e] }
end

或者:

result.each do |result|
  keys = domain == 'social' ? %w[positive negative declined] : %w[high medium low]
  hash[result['date']] = keys.each_with_object(Hash.new(0)) { |e, h| h[e] = result[e] }
end

答案 2 :(得分:1)

result.each do |result|
  hash[result['date']] = result.slice(
    *case domain
    when "social" then %w[positive negative declined]
    when "motivation" then %w[high medium low]
    end
  )
end