Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

ActiveSupport | String#indent

概要

String#indent

詳細

String#indent について

String#indent

テキストをインデントしてくれる。

内部のインデント形式に合わせてスペースインデントやタブインデントを行ってくれる。
インデント形式を明示的に指定することも可能。

サンプル

# encoding: utf-8
require 'active_support/core_ext/string/indent'

def get_space_hoge
  space_hoge = <<-EOS.indent(2)
ほげ1
  ひげ1
    はげ1
    はげ2
  ひげ2
ほげ2
  EOS
end

def get_tab_hoge
  space_hoge = <<-EOS.indent(2)
ほげ1
  ひげ1
    はげ1
    はげ2
  ひげ2
ほげ2
  EOS
end

def get_space_hige(format)
  space_hoge = <<-EOS.indent(2, format)
ほげ1
  ひげ1
    はげ1
    はげ2
  ひげ2
ほげ2
  EOS
end

puts get_space_hoge
puts get_tab_hoge
puts get_space_hige("@")

str = "hoge\n\thoge\n\t\thoge"
puts str.indent(1)
puts str.indent(1, "@")
puts str # imutable版のindentは元の文字列を変更しない
puts str.indent!(1, "@")
puts str # mutable版のindentは元の文字列を変更する

出力

  ほげ1
    ひげ1
      はげ1
      はげ2
    ひげ2
  ほげ2
		ほげ1
			ひげ1
				はげ1
				はげ2
			ひげ2
		ほげ2
@@ほげ1
@@  ひげ1
@@    はげ1
@@    はげ2
@@  ひげ2
@@ほげ2
	hoge
		hoge
			hoge
@hoge
@	hoge
@		hoge
hoge
	hoge
		hoge
@hoge
@	hoge
@		hoge
@hoge
@	hoge
@		hoge