views:

7697

answers:

2

Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent.

The opposite of

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

or

"0A".hex
=>10

I know how to roll my own, but it's probably more efficient to use a built in ruby function

+6  A: 

How about:

i = 20

"%x" % i
flxkid
Thanks for showing this, I needed something that would get me a fixed length string prepended with '0'. ex: "%02X" % 10 #=> "0A"
Aaron Hinni
+19  A: 

how about this:

10.to_s(16) #=> "a"
255.to_s(16) #=> "ff"

Documented here [edit - my bad I copy pasted my link too fast and put the String one instead of the Fixnum one]

Jean
That's the answer I was looking for but it isn't documented on the linked pagestr.to_s => stris specified as not accepting parameters and has"Returns the receiver."as the only documentation, but it seems to work
Matt Haughton
sorry about that copy paste mistake of course to_s on string doesn't take arguments but on Fixnum it does :)
Jean
Ah, I was looking under Integer for a .to_s method and couldn't find one. I'll look under Fixnum next time as well
Matt Haughton
Thanks for this answer.
jrhicks