module Nuggets::String::FormatMixin

Constants

FORMAT_RE
PREFIX

Public Instance Methods

format(hash) → aString click to toggle source
format { |directive| ... } → aString

Replace format directives in str.

If hash given, uses value of directive key (String or Symbol) as replacement value. Raises KeyError if directive key not found.

If block given, uses result of directive yielded to block as replacement value. Raises ArgumentError if block returns no value.

# File lib/nuggets/string/format_mixin.rb, line 46
def format(hash = nil)
  replace = lambda { |&b| gsub(FORMAT_RE) {
    (k = $1 || $2) == PREFIX ? k : b[k] } }

  hash ? replace.() { |k| hash.fetch(k) {
    hash.fetch(k.to_sym) { raise(KeyError, "key not found: #{k}") } } } :
  block_given? ? replace.() { |k| yield k or
    raise(ArgumentError, "malformed format string - #{$&}") } :
    raise(ArgumentError, 'wrong number of arguments (given 0, expected 1)')
end