Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/hexutils.rb
Overview
todo/check:
allow/ignore whitespaces [ \t\n\r] in hex strings why? why not?
or add option with ignore e.g. ':' or such - why? why not?
Instance Method Summary collapse
- #hex? ⇒ Boolean (also: #is_hex?)
- #to_hex ⇒ Object (also: #hex)
Instance Method Details
#hex? ⇒ Boolean Also known as: is_hex?
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/hexutils.rb', line 16 def hex? if self.empty? ## make empty string (e.g.'') a valid hex string - why? why not? ## note: 0x (prefix only) is NOT a valid hex string true elsif self =~ /\A(0[xX])?[0-9a-fA-F]+\z/ ## note: allow 0x0 or 0xf too or 0xfff or 0x123 ## that is uneven hexstrings ## a byte assumes always two chars true else false end end |
#to_hex ⇒ Object Also known as: hex
32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/hexutils.rb', line 32 def to_hex if self.empty? ## change encoding to utf_8 - why? why not? ## always return a new string why? why not? '' ## note: assume utf_8 encoding for new string else ## note: always return a hex string with default encoding e.g. utf-8 - why? why not? ### check if unpack always works on bytes (or .b required???) self.unpack( 'H*' ).first.force_encoding( Encoding::UTF_8 ) end end |