Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/rotor_machine/string_extensions.rb
Overview
String extensions used by the RotorMachine::Machine to format output.
Instance Method Summary collapse
-
#in_blocks_of(block_size = 5, rejoin = true) ⇒ Object
(also: #in_blocks)
Break a string into blocks of a certain number of characters.
-
#is_number? ⇒ Boolean
Test if the string is a number.
-
#is_uniq? ⇒ Boolean
(also: #uniq?)
Detect if a string has any duplicated characters.
-
#tokenize ⇒ Object
Break a string into words, including handling quoted substrings.
-
#uncolorize ⇒ Object
Strip ANSI color sequences from the string.
Instance Method Details
#in_blocks_of(block_size = 5, rejoin = true) ⇒ Object Also known as: in_blocks
Break a string into blocks of a certain number of characters.
Encrypted text is often presented in blocks of 5 characters to disguise word lengths in the ciphertext/plaintext. This method gives Ruby strings the ability to break themselves into blocks of no more than a specified number of characters.
By default, the string is rejoined into a single string, with each character group separated by a space. To return the string as an array of chunks instead, pass a false value for the rejoin argument.
36 37 38 39 40 41 42 |
# File 'lib/rotor_machine/string_extensions.rb', line 36 def in_blocks_of(block_size=5, rejoin=true) if rejoin self.chars.reject{|s| s.match(/\s/)}.each_slice(block_size).map(&:join).join(" ") else self.chars.reject{|s| s.match(/\s/)}.each_slice(block_size).map(&:join) end end |
#is_number? ⇒ Boolean
Test if the string is a number.
60 61 62 |
# File 'lib/rotor_machine/string_extensions.rb', line 60 def is_number? true if Float(self) rescue false end |
#is_uniq? ⇒ Boolean Also known as: uniq?
Detect if a string has any duplicated characters
12 13 14 |
# File 'lib/rotor_machine/string_extensions.rb', line 12 def is_uniq? self.chars.uniq.length == self.chars.length end |
#tokenize ⇒ Object
Break a string into words, including handling quoted substrings.
49 50 51 52 53 54 |
# File 'lib/rotor_machine/string_extensions.rb', line 49 def tokenize self. split(/\s(?=(?:[^'"]|'[^']*'|"[^"]*")*$)/). select {|s| not s.empty? }. map {|s| s.gsub(/(^ +)|( +$)|(^["']+)|(["']+$)/,'')} end |
#uncolorize ⇒ Object
Strip ANSI color sequences from the string.
69 70 71 72 73 74 |
# File 'lib/rotor_machine/string_extensions.rb', line 69 def uncolorize pattern = /\033\[([0-9]+);([0-9]+);([0-9]+)m(.+?)\033\[0m|([^\033]+)/m self.scan(pattern).inject("") do |str, match| str << (match[3] || match[4]) end end |