Sha256: 9192c9c35dda3eca8b21ac1e6d69d165e33703fe78f7e59de600bae4f8c1c3cb

Contents?: true

Size: 861 Bytes

Versions: 13

Compression:

Stored size: 861 Bytes

Contents

class String

  # Expands tabs to +n+ spaces. Non-destructive. If +n+ is 0,
  # then tabs are simply removed. Raises an exception if +n+
  # is negative.
  #
  #   "\t\tHey".expand_tabs(2)  #=> "    Hey"
  #
  # Thanks to GGaramuno for a more efficient algorithm. Very nice.
  #
  # CREDIT: Gavin Sinclair, Noah Gibbs, GGaramuno
  #
  # TODO: Don't much care for the name String#expand_tabs.
  # What about a more concise name like #detab?

  def expand_tabs(n=8)
    n = n.to_int
    raise ArgumentError, "n must be >= 0" if n < 0
    return gsub(/\t/, "") if n == 0
    return gsub(/\t/, " ") if n == 1
    str = self.dup
    while
      str.gsub!(/^([^\t\n]*)(\t+)/) { |f|
        val = ( n * $2.size - ($1.size % n) )
        $1 << (' ' * val)
      }
    end
    str
  end

  # Singular form of #expand_tabs.
  alias_method :expand_tab, :expand_tabs

end

Version data entries

13 entries across 12 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/string/expand_tab.rb
facets-3.1.0 lib/core/facets/string/expand_tab.rb
facets-3.0.0 lib/core/facets/string/expand_tab.rb
facets-2.9.3 lib/core/facets/string/expand_tab.rb
facets-2.9.2 lib/core/facets/string/expand_tab.rb
facets-2.9.2 src/core/facets/string/expand_tab.rb
facets-2.9.1 lib/core/facets/string/expand_tab.rb
facets-2.9.0 lib/core/facets/string/expand_tab.rb
facets-2.9.0.pre.2 lib/core/facets/string/expand_tab.rb
facets-2.9.0.pre.1 lib/core/facets/string/expand_tab.rb
facets-2.8.4 lib/core/facets/string/expand_tab.rb
facets-2.8.3 lib/core/facets/string/expand_tab.rb
facets-2.8.2 lib/core/facets/string/expand_tab.rb