Read more

Ruby: Indent a string

Henning Koch
February 13, 2012Software engineer at makandra GmbH

Copy the attached file to config/initializers/indent_string.rb and you can say

"foo".indent(4) # "    foo"
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Note you will find many simpler implementations of this method on the Interweb. They probably won't do what you want in edge cases, fuck up trailing whitespace, etc. The implementation in this card has the following behavior:

describe '#indent' do

  it 'should indent the string by the given number of spaces' do
    "foo".indent(2).should == "  foo"
  end

  it 'should indent multiple lines line by line' do
    "foo\nbar\n".indent(2).should == "  foo\n  bar\n"
  end

  it 'should indent blank lines' do
    "foo\n\nbar\n".indent(2).should == "  foo\n  \n  bar\n"
  end

  it 'should not add whitespace at the end' do
    "foo\nbar".indent(2).should == "  foo\n  bar"
  end

  it 'should take an optional second argument which changes the character used for indentation' do
    "foo".indent(2, '.').should == "..foo"
  end

end
Posted by Henning Koch to makandra dev (2012-02-13 16:18)