Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/active_support/core_ext/string/indent.rb
Instance Method Summary collapse
-
#indent(amount, indent_string = nil, indent_empty_lines = false) ⇒ Object
Indents the lines in the receiver:.
-
#indent!(amount, indent_string = nil, indent_empty_lines = false) ⇒ Object
Same as
indent, except it indents the receiver in-place.
Instance Method Details
#indent(amount, indent_string = nil, indent_empty_lines = false) ⇒ Object
Indents the lines in the receiver:
"def some_method\n some_code\nend\n".indent(2)
# =>
def some_method
some_code
end
The second argument, indent_string, specifies which indent string to use. The default is nil, which tells the method to make a guess by peeking at the first indented line, and fallback to a space if there is none.
" foo".indent(2) # => " foo"
"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, "\t") # => "\t\tfoo"
While indent_string is typically one space or tab, it may be any string.
The third argument, indent_empty_lines, is a flag that says whether empty lines should be indented. Default is false.
"foo\n\nbar".indent(2) # => " foo\n\n bar"
"foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
40 41 42 |
# File 'lib/active_support/core_ext/string/indent.rb', line 40 def indent(amount, indent_string=nil, indent_empty_lines=false) dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)} end |
#indent!(amount, indent_string = nil, indent_empty_lines = false) ⇒ Object
Same as indent, except it indents the receiver in-place.
Returns the indented string, or nil if there was nothing to indent.
5 6 7 8 9 |
# File 'lib/active_support/core_ext/string/indent.rb', line 5 def indent!(amount, indent_string=nil, indent_empty_lines=false) indent_string = indent_string || self[/^[ \t]/] || ' ' re = indent_empty_lines ? /^/ : /^(?!$)/ gsub!(re, indent_string * amount) end |