~/rubytesting$ ./h2d.rb 0x1F 0x2A 31 42En caso de que alguno de los argumentos no contenga un número hexadecimal deberá producir una excepción:
~/rubytesting$ ./h2d.rb 0x1F 0x2Z3 0x2A 31 ./h2d.rb:4:in `h2d': Not an hex number: 0x2Z3 (SyntaxError) from ./h2d.rb:8 from ./h2d.rb:8:in `each' from ./h2d.rb:8
hex
puede ayudarle:
>> "0x1f".hex => 31Si tiene la documentación instalada (si no es el caso, puede encontrar la documentación de Ruby en http://ruby-doc.org/ ), puede escribir:
$ ri -T String#hex ------------------------------------------------------------- String#hex str.hex => integer ------------------------------------------------------------------------ Treats leading characters from _str_ as a string of hexadecimal digits (with an optional sign and an optional +0x+) and returns the corresponding number. Zero is returned on error. "0x0a".hex #=> 10 "-1234".hex #=> -4660 "0".hex #=> 0 "wombat".hex #=> 0o bien en
pry
:
[18] pry(main)> show-doc "x".hex From: string.c (C Method): Owner: String Visibility: public Signature: hex() Number of lines: 8 Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error. "0x0a".hex #=> 10 "-1234".hex #=> -4660 "0".hex #=> 0 "wombat".hex #=> 0
[11] pry(main)> show-method "x".hex From: string.c (C Method): Owner: String Visibility: public Number of lines: 10 static VALUE rb_str_hex(VALUE str) { rb_encoding *enc = rb_enc_get(str); if (!rb_enc_asciicompat(enc)) { rb_raise(rb_eEncCompatError, "ASCII incompatible encoding: %s", rb_enc_name(enc)); } return rb_str_to_inum(str, 16, FALSE); }
raise SyntaxError, "Not an hex number: #{h}" if h !~ /^\s*0x[\dA-F]+\s*$/iLa condición
h !~ /^\s*0x[\dA-F]+\s*$/i
se lee
h
no casa con la expresión regular /^\s*0x[\dA-F]+\s*$/i
.
Esta expresión regular casa con las cadenas que comienzan por blancos,
seguidos de 0x
y dígitos y letras entre A
y F
.
[12] pry(main)> h = "0x1f" => "0x1f" [13] pry(main)> h =~ /^\s*0x[\dA-F]+\s*$/i => 0 [14] pry(main)> h = "0x0x"; h =~ /^\s*0x[\dA-F]+\s*$/i => nil [15] pry(main)> h = "0x0x4d"; h =~ /\s*0x[\dA-F]+\s*$/i => 2 [16] pry(main)> h = "0x0x4d"; h =~ /\s*0x[A-F]+\s*$/i => nil [17] pry(main)> h = "0x0xd"; h =~ /\s*0x[A-F]+\s*$/i => 2
each
:
ARGV.each { |h| puts(h2d(h)) }