Sha256: d76c952f69e98738f788e7005700e0bff079e29012a27109681310b55c55e73b

Contents?: true

Size: 1.41 KB

Versions: 112

Compression:

Stored size: 1.41 KB

Contents

# encoding: utf-8

# String
class String
  # surround string.
  #
  # ==== Options
  #
  # * <tt>:top_bottom</tt> - set top and bottom charactor
  # * <tt>:side</tt> - set right and left charactor
  #
  # ==== Examples
  #
  # single line, no option case
  #
  #   'hoge'.surround
  #
  # result
  #
  #   ------
  #   |hoge|
  #   ------
  #
  # multi line, no option case
  #
  #   "hoge\na".surround
  #
  # result
  #
  #   ------
  #   |hoge|
  #   |a   |
  #   ------
  #
  # single line, both option case
  #
  #   'hoge'.surround top_bottom: '=', side: '!'
  #
  # result
  #
  #   ======
  #   !hoge!
  #   ======
  #
  def surround(options = { top_bottom: '-', side: '|' })
    top_bottom = init_top_bottom(options)
    side = init_side(options)
    inner_width = line_max
    top_bottom = top_bottoms(top_bottom, inner_width)
    ret = *each_line.reduce(["#{top_bottom}"]) { |ret, line|ret << "#{side}#{line.chomp.ljust(inner_width)}#{side}" }
    ret.push("#{top_bottom}").join("\n")
  end

  private

  def init_top_bottom(options)
    options[:top_bottom].nil? ? '-' : options[:top_bottom]
  end

  def init_side(options)
    options[:side].nil? ? '|' : options[:side]
  end

  def top_bottoms(top_bottom, inner_width)
    top_bottom * (inner_width + 2)
  end

  def line_max
    return 0 if self.empty?
    each_line.max_by { |v|v.size }.chomp.size
  end
end

Version data entries

112 entries across 112 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.70 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.69 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.68 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.67 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.66 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.65 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.64 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.63 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.62 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.61 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.60 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.59 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.58 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.57 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.56 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.55 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.54 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.53 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.52 lib/open_classes/string/surround.rb
tbpgr_utils-0.0.51 lib/open_classes/string/surround.rb