Module: NRSER::Char

Defined in:
lib/nrser/char.rb,
lib/nrser/char.rb

Overview

A place to put things that work with characters.

**_This is ALL based around UTF-8 by default_**

Defined Under Namespace

Classes: AlphaNumericSub, Special

Constant Summary collapse

CONTROL_RE =

Regexp that matches a control character.

Returns:

  • (Regexp)
/[[:cntrl:]]/
ALL_CONTROL_RE =

Regexp that matches when all characters are control characters.

NOTE This will match the empty string.

Returns:

  • (Regexp)
/\A[[:cntrl:]]*\z/
HEX_RE =
/\A[0-9a-f]+\z/i
NULL =

Special character info for the NULL character (zero byte in string).

Special.new \
char:         "\u0000",
names:         ['NULL', 'NUL', '<control-0000>'],
caret:        '^@',
symbol:       ''

Class Method Summary collapse

Class Method Details

.control?(char) ⇒ Boolean

Test if string is a control character (returns ‘false` if length > 1).

Parameters:

  • char (String)

    String to test.

Returns:

  • (Boolean)

    ‘true` if `char` is a control character.



77
78
79
# File 'lib/nrser/char.rb', line 77

def self.control? char
  char.length == 1 && CONTROL_RE.match( char )
end

.from(source) ⇒ String

Convert hex string to UTF-8 character (length 1 string).

Parameters:

  • source (String | Integer)

    Hexadecimal (base-16) number represented as a string or a non-negative integer.

Returns:

  • (String)

    UTF-8 character.

Raises:

  • When conversion can’t be performed.



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/nrser/char.rb', line 131

def self.from source
  case source
  when HEX_RE
    from_hex source
  when Integer
    from_i source
  else
    raise ArgumentError.new binding.erb <<-END
      Expected hex String like '12AB' or Integer, got <%= source.class %>:
      
          <%= source.pretty_inspect %>
      
    END
  end
end

.from_hex(hex) ⇒ String

Convert hex string to UTF-8 character (length 1 string).

Parameters:

  • hex (String)

    Hexadecimal (base-16) number represented as a string.

Returns:

  • (String)

    UTF-8 character.

Raises:

  • When conversion can’t be performed.



115
116
117
# File 'lib/nrser/char.rb', line 115

def self.from_hex hex
  from_i hex.to_i( 16 )
end

.from_i(int) ⇒ String

Convert integer to UTF-8 character (length 1 string).

Parameters:

  • int (Integer)

    Integer (decimal/base-10) representation of the character.

Returns:

  • (String)

    UTF-8 character.

Raises:

  • When conversion can’t be performed.



96
97
98
# File 'lib/nrser/char.rb', line 96

def self.from_i int
  int.chr Encoding::UTF_8
end