Sha256: 4b31524b40cd6e5166a337e0fec135474b3c1508846f8fa577f21211924e8661

Contents?: true

Size: 1.26 KB

Versions: 176

Compression:

Stored size: 1.26 KB

Contents

module Tins
  module Subhash
    # Create a subhash from this hash, that only contains key-value pairs
    # matching +patterns+ and return it. +patterns+ can be for example /^foo/
    # to put 'foobar' and 'foobaz' or 'foo'/:foo to put 'foo' into the subhash.
    #
    # If a block is given this method yields to it after the first pattern
    # matched with a 3-tuple of +(key, value, match_data)+ using the return
    # value of the block as the value of the result hash. +match_data+ is a
    # MatchData instance if the matching pattern was a regular rexpression
    # otherwise it is nil.
    def subhash(*patterns)
      patterns.map! do |pat|
        pat = pat.to_sym.to_s if pat.respond_to?(:to_sym)
        pat.respond_to?(:match) ? pat : pat.to_s
      end
      result =
        if default_proc
          self.class.new(&default_proc)
        else
          self.class.new(default)
        end
      if block_given?
        each do |k, v|
          patterns.each { |pat|
            if pat === k.to_s
              result[k] = yield(k, v, $~)
              break
            end
          }
        end
      else
        each do |k, v|
          result[k] = v if patterns.any? { |pat| pat === k.to_s }
        end
      end
      result
    end
  end
end

require 'tins/alias'

Version data entries

176 entries across 158 versions & 9 rubygems

Version Path
tins-1.38.0 lib/tins/subhash.rb
tins-1.37.1 lib/tins/subhash.rb
tins-1.37.0 lib/tins/subhash.rb
tins-1.36.1 lib/tins/subhash.rb
tins-1.36.0 lib/tins/subhash.rb
tins-1.35.0 lib/tins/subhash.rb
tins-1.34.0 lib/tins/subhash.rb
tins-1.33.0 lib/tins/subhash.rb
tdiary-5.2.4 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/subhash.rb
tins-1.32.1 lib/tins/subhash.rb
tins-1.32.0 lib/tins/subhash.rb
tdiary-5.2.3 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/subhash.rb
tdiary-5.2.2 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/subhash.rb
tins-1.31.1 lib/tins/subhash.rb
tdiary-5.2.1 vendor/bundle/ruby/3.1.0/gems/tins-1.31.0/lib/tins/subhash.rb
tins-1.31.0 lib/tins/subhash.rb
tins-1.30.0 lib/tins/subhash.rb
tdiary-5.2.0 vendor/bundle/ruby/3.0.0/gems/tins-1.29.1/lib/tins/subhash.rb
tdiary-5.2.0 vendor/bundle/ruby/2.7.0/gems/tins-1.29.1/lib/tins/subhash.rb
tdiary-5.1.7 vendor/bundle/ruby/3.0.0/gems/tins-1.29.1/lib/tins/subhash.rb