Sha256: 167dba292f596be04e6dcd0aea1a0dbc1be3be1da92431d3e20af49403f550de

Contents?: true

Size: 960 Bytes

Versions: 5

Compression:

Stored size: 960 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?(Fixnum) || (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?(Fixnum) ? val : val['frequency'] || val[:frequency]
      s += freq
      return option if s > seed
    end
    nil
  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
bootstripe-0.2.20 lib/bootstripe/hash_additions.rb
bootstripe-0.2.19 lib/bootstripe/hash_additions.rb
bootstripe-0.2.18 lib/bootstripe/hash_additions.rb
bootstripe-0.2.17 lib/bootstripe/hash_additions.rb
bootstripe-0.2.16 lib/bootstripe/hash_additions.rb