Class: Ncase::Words

Inherits:
Object
  • Object
show all
Defined in:
lib/ncase/words.rb

Overview

Implements efficient conversion of a string into multiple case styles.

By default will guess the separator in the string:

  1. If the string contains spaces ‘\x20’, any sequence of whitespace is a separator.

  2. If the string contains hyphens ‘-’ or underscores ‘_’, whichever is more frequent is a separator.

  3. A case-switch is a separator.

Examples:

Convert a string into PascalCase and snake_case

require "ncase"

w = Ncase::Words.new("this is a test string")
p w.pascal_case  # => "ThisIsATestString"
p w.snake_case   # => "this_is_a_test_string"

Instance Method Summary collapse

Constructor Details

#initialize(str, separator: nil) ⇒ Words

Returns a new instance of Words.

See Also:

  • String#split


25
26
27
28
29
# File 'lib/ncase/words.rb', line 25

def initialize(str, separator: nil)
  sstr = str.strip
  separator ||= guess_separator(sstr)
  @words = sstr.split(separator)
end

Instance Method Details

#camel_caseString



32
33
34
35
36
37
38
# File 'lib/ncase/words.rb', line 32

def camel_case
  return "" if @words.empty?

  @words.each(&:capitalize!)
  @words.first.downcase!
  @words.join
end

#inver_title_caseString



81
82
83
# File 'lib/ncase/words.rb', line 81

def inver_title_case
  @words.each(&:capitalize!).each(&:swapcase!).join(" ")
end

#kebab_caseString



46
47
48
# File 'lib/ncase/words.rb', line 46

def kebab_case
  @words.each(&:downcase!).join("-")
end

#lower_caseString



56
57
58
# File 'lib/ncase/words.rb', line 56

def lower_case
  @words.each(&:downcase!).join(" ")
end

#pascal_caseString



41
42
43
# File 'lib/ncase/words.rb', line 41

def pascal_case
  @words.each(&:capitalize!).join
end

#random_caseString



86
87
88
89
90
91
# File 'lib/ncase/words.rb', line 86

def random_case
  @words.join(" ")
        .chars
        .each { |c| rand(2).zero? ? c.downcase! : c.upcase! }
        .join
end

#snake_caseString



66
67
68
# File 'lib/ncase/words.rb', line 66

def snake_case
  @words.each(&:downcase!).join("_")
end

#title_caseString



76
77
78
# File 'lib/ncase/words.rb', line 76

def title_case
  @words.each(&:capitalize!).join(" ")
end

#upper_caseString



61
62
63
# File 'lib/ncase/words.rb', line 61

def upper_case
  @words.each(&:upcase!).join(" ")
end

#upper_kebab_caseString



51
52
53
# File 'lib/ncase/words.rb', line 51

def upper_kebab_case
  @words.each(&:upcase!).join("-")
end

#upper_snake_caseString



71
72
73
# File 'lib/ncase/words.rb', line 71

def upper_snake_case
  @words.each(&:upcase!).join("_")
end