Module: Corefines::String::Indent

Defined in:
lib/corefines/string.rb

Instance Method Summary collapse

Instance Method Details

#indent(amount, indent_str = nil, indent_empty_lines = false) ⇒ String

Returns an indented copy of this string.

Examples:

"foo".indent(2)           # => "  foo"
"  foo".indent(2)         # => "    foo"
"foo\n\t\tbar".indent(2)  # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, '.')      # => "..foo"
"foo\n\nbar".indent(2)    # => "  foo\n\n  bar"
"foo\n\nbar".indent(2, nil, true)  # => "  foo\n  \n  bar"

269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/corefines/string.rb', line 269

module Indent
  refine ::String do
    def indent(amount, indent_str = nil, indent_empty_lines = false)
      dup.tap { |str| str.indent! amount, indent_str, indent_empty_lines }
    end

    def indent!(amount, indent_str = nil, indent_empty_lines = false)
      indent_str = indent_str || self[/^[ \t]/] || ' '
      re = indent_empty_lines ? /^/ : /^(?!$)/
      gsub! re, indent_str * amount
    end
  end
end

#indent!(amount, indent_str = nil, indent_empty_lines = false) ⇒ String

Returns the indented string, or nil if there was nothing to indent. This is same as #indent, except it indents the receiver in-place.

See Also:


269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/corefines/string.rb', line 269

module Indent
  refine ::String do
    def indent(amount, indent_str = nil, indent_empty_lines = false)
      dup.tap { |str| str.indent! amount, indent_str, indent_empty_lines }
    end

    def indent!(amount, indent_str = nil, indent_empty_lines = false)
      indent_str = indent_str || self[/^[ \t]/] || ' '
      re = indent_empty_lines ? /^/ : /^(?!$)/
      gsub! re, indent_str * amount
    end
  end
end