Sha256: d918f8bb81e2b8cec6636d4d7bc885b92f05d9c4b8753fd56d1da5ad68290266

Contents?: true

Size: 966 Bytes

Versions: 1

Compression:

Stored size: 966 Bytes

Contents

class Hash
  def nested_keys
    keys = []
    self.each do |key, value|
      keys << key
      if value.is_a?(Hash)
        keys += value.nested_keys
      end
    end
    keys
  end

  def deep_push_merge!(other)
    other.each_pair do |key, other_val|
      val = self[key]
      case val
      when Array
        self[key] = val + [*other_val]
      when Hash
        val.deep_push_merge! other_val
      else
        self[key] = other_val unless other_val.nil?
      end
    end
  end

  def random_by_frequency(seed = nil)
    options = select{ |k,v| v.is_a?(Numeric) || (v.is_a?(Hash) && (v['frequency'] || v[:frequency])) }
    total_frequency = options.map{ |k,v| v.is_a?(Hash) ? v['frequency'] || v[:frequency] : v }.sum
    seed ||= (rand * total_frequency)

    s = 0
    options.find do |option, val|
      freq = val.is_a?(Numeric) ? val : val['frequency'] || val[:frequency]
      s += freq
      return option if s > seed
    end
    nil
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bootstripe-0.2.23 lib/bootstripe/hash_additions.rb