Skip to content

List Converter — Ruby source

Transform a list between separators (newline, comma, space, pipe, semicolon, tab) with trim, dedupe, sort, and empty-removal options. Runs entirely in your browser, with a shareable link.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# List Converter — split/trim/dedup/sort/join between separators — Ruby port of the list-converter tool.

module ListConverter
  SEP = {
    'newline' => "\n", 'comma' => ',', 'space' => ' ', 'pipe' => '|',
    'semicolon' => ';', 'tab' => "\t"
  }.freeze

  # fetch(name, name): unknown names pass through as a literal separator,
  # the TS resolveSep behavior.
  def self.resolve_sep(name) = SEP.fetch(name, name)

  # Convert a list between separators: split -> (trim) -> (drop empties) ->
  # (dedup, first occurrence wins) -> (stable sort) -> join. Mirrors the Go twin.
  def self.convert(input, from: 'newline', to: 'comma', trim: false, remove_empty: false,
                   unique: false, sort: false, case_insensitive: false)
    items = input.split(resolve_sep(from), -1) # -1 keeps trailing empties

    items.map!(&:strip) if trim
    items.reject!(&:empty?) if remove_empty
    if unique # seen holds keys only; items keep their original casing
      seen = {}
      items = items.filter_map do |s|
        key = case_insensitive ? s.downcase : s
        next if seen.key?(key)

        seen[key] = true
        s
      end
    end
    if sort # sort_by is not stable, so equal keys tie-break on index
      items = items.each_with_index
                   .sort_by { |s, i| [case_insensitive ? s.downcase : s, i] }
                   .map(&:first)
    end
    items.join(resolve_sep(to))
  end
end

if $PROGRAM_NAME == __FILE__
  # "b\n a \nB\na\n\nc" -> trim, drop empties, case-insensitive dedup+sort
  puts ListConverter.convert("b\n a \nB\na\n\nc",
                             trim: true, remove_empty: true, unique: true,
                             sort: true, case_insensitive: true) # => a,b,c
end

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →