Module: Nuggets::String::WcMixin

Included in:
String
Defined in:
lib/nuggets/string/wc_mixin.rb

Instance Method Summary collapse

Instance Method Details

#byte_countObject Also known as: wc_c

call-seq:

str.byte_count => anInteger

Count number of bytes in str.



62
63
64
# File 'lib/nuggets/string/wc_mixin.rb', line 62

def byte_count
  respond_to?(:bytesize) ? bytesize : count_by_re(//n) - 1
end

#char_countObject Also known as: wc_m

call-seq:

str.char_count => anInteger

Count number of characters in str.



71
72
73
# File 'lib/nuggets/string/wc_mixin.rb', line 71

def char_count
  count_by_re(/./um)
end

#count_by_re(re) ⇒ Object

call-seq:

str.count_by_re(re) => anInteger

Count number of occurrences of re in str.



80
81
82
# File 'lib/nuggets/string/wc_mixin.rb', line 80

def count_by_re(re)
  scan(re).size
end

#count_by_re2(re) ⇒ Object

call-seq:

str.count_by_re2(re) => anInteger

A more memory-efficient version of #count_by_re.



88
89
90
91
92
# File 'lib/nuggets/string/wc_mixin.rb', line 88

def count_by_re2(re)
  count = 0
  scan(re) { |_| count += 1 }
  count
end

#line_countObject Also known as: wc_l

call-seq:

str.line_count => anInteger

Count number of lines in str.



44
45
46
# File 'lib/nuggets/string/wc_mixin.rb', line 44

def line_count
  count_by_re(/#{$/}/)
end

#wcObject

call-seq:

str.wc => anArray

Count number of lines, words, and bytes in str.



36
37
38
# File 'lib/nuggets/string/wc_mixin.rb', line 36

def wc
  [wc_l, wc_w, wc_c]
end

#word_countObject Also known as: wc_w

call-seq:

str.word_count => anInteger

Count number of words in str.



53
54
55
# File 'lib/nuggets/string/wc_mixin.rb', line 53

def word_count
  count_by_re(/\S+/)
end