Module: CommandKit::Printing::Lists

Includes:
Indent
Defined in:
lib/command_kit/printing/lists.rb

Overview

Methods for printing lists.

Examples

include Printing::Lists

def main
  print_list %w[foo bar baz]
  # * foo
  # * bar
  # * baz

  list = ['item 1', 'item 2', ['sub-item 1', 'sub-item 2']]
  print_list(list)
  # * item 1
  # * item 2
  #   * sub-item 1
  #   * sub-item 2

  print_list %w[foo bar baz], bullet: '-'
  # - foo
  # - bar
  # - baz
end

Since:

  • 0.4.0

Instance Method Summary collapse

Methods included from Indent

#indent, #initialize, #puts

Instance Method Details

Prints a bulleted list of items.

Examples:

print_list %w[foo bar baz]
# * foo
# * bar
# * baz

print a nested list:

list = ['item 1', 'item 2', ['sub-item 1', 'sub-item 2']]
print_list(list)
# * item 1
# * item 2
#   * sub-item 1
#   * sub-item 2

with a custom bullet character:

print_list %w[foo bar baz], bullet: '-'
# - foo
# - bar
# - baz

Parameters:

  • list (Array<#to_s, Array>)

    The list of items to print.

  • bullet (String) (defaults to: '*')

    The bullet character to use for line item.

Since:

  • 0.4.0



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/command_kit/printing/lists.rb', line 69

def print_list(list, bullet: '*')
  list.each do |item|
    case item
    when Array
      indent { print_list(item, bullet: bullet) }
    else
      first_line, *rest = item.to_s.lines(chomp: true)

      # print the bullet only on the first list
      puts "#{bullet} #{first_line}"

      # indent the remaining lines
      indent(bullet.length + 1) do
        rest.each do |line|
          puts line
        end
      end
    end
  end
end