Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/rotor_machine/string_extensions.rb

Overview

String extensions used by the RotorMachine::Machine to format output.

Instance Method Summary collapse

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.

Parameters:

  • block_size (Numeric) (defaults to: 5)

    The maximum size of each block. Defaults to 5-character blocks if not provided.

  • rejoin (Boolean) (defaults to: true)

    True to join the blocks back into a single string, false to return an array of chunks instead. Defaults to true.

Returns:

  • The string with each chunk separated by spaces, or an array of chunks if rejoin is false.



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.

Returns:

  • (Boolean)

    True if the string is a number, false otherwise.



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

Returns:

  • (Boolean)

    True if the string has no duplicated characters, false otherwise.



12
13
14
# File 'lib/rotor_machine/string_extensions.rb', line 12

def is_uniq?
  self.chars.uniq.length == self.chars.length
end

#tokenizeObject

Break a string into words, including handling quoted substrings.

Returns:

  • An array of tokens, if the string can be tokenized.



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

#uncolorizeObject

Strip ANSI color sequences from the string.

Returns:

  • The string with ANSI color sequences escaped.



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