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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)