Konwersja liczby całkowitej do ciągu szesnastkowego w Ruby

Czy istnieje wbudowany sposób konwersji liczby całkowitej w Rubim na jej szesnastkowy odpowiednik?

Coś w rodzaju przeciwieństwa String#to_i:

"0A".to_i(16) #=>10

Jak być może:

"0A".hex #=>10

Wiem, jak to zrobić, ale prawdopodobnie bardziej wydajne jest użycie wbudowanej funkcji Ruby.

Author: Andrew Marshall, 2008-09-17

5 answers

Możesz dać to_s baza inna niż 10:

10.to_s(16)  #=> "a"
 292
Author: Jean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-26 04:01:53

Jak o użyciu %/sprintf:

i = 20
"%x" % i  #=> "14"
 83
Author: flxkid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-26 04:10:44

Podsumowując:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"
 66
Author: user495470,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-24 22:54:59

Oto inne podejście:

sprintf("%02x", 10).upcase

Zobacz dokumentację sprintf tutaj: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

 11
Author: Ultrasaurus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-30 07:15:22

Na wszelki wypadek masz preferencje dotyczące formatowania liczb ujemnych:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"
 3
Author: tool maker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-24 10:49:05