Ruby 2.4.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Stringクラス > hex

instance method String#hex

hex -> Integer[permalink][rdoc]

文字列に 16 進数で数値が表現されていると解釈して整数に変換します。接頭辞 "0x", "0X" とアンダースコアは無視されます。文字列が [_0-9a-fA-F] 以外の文字を含むときはその文字以降を無視します。

self が空文字列のときは 0 を返します。



p "10".hex    # => 16
p "ff".hex    # => 255
p "0x10".hex  # => 16
p "-0x10".hex # => -16

p "xyz".hex   # => 0
p "10z".hex   # => 16
p "1_0".hex   # => 16

p "".hex      # => 0

[SEE_ALSO] String#oct, String#to_i, String#to_f, Kernel.#Integer, Kernel.#Float

このメソッドの逆に数値を文字列に変換するには Kernel.#sprintf, String#%, Integer#to_s などを使ってください。