将数字转换为ASCII字符串的最简洁的Ruby方法是什么?
例如,a = 0x68656c6c6f应该成为a = "hello".
在没有库的普通C中,我会使用一个0xFF掩码,我一直在移动.不知怎的,我觉得Ruby有更短/更不明确的方式来做到这一点.
我正在使用Ruby 1.8.7.
["%x" % 0x68656c6c6f].pack("H*")
Run Code Online (Sandbox Code Playgroud)
更新:另一个疯狂的想法,在你的情况下可能是矫枉过正,但这个想法适用于前导零.事实上,它只是转移,而是可以进行各种功能等一起使用map,inject,each等.
class S
include Enumerable
def initialize(i)
@i = i
end
def each(&block)
while @i > 0
@i, b = @i.divmod(256)
block[b.chr]
end
end
end
S.new(0x0168656c6c6f).inject{ |a, c| c + a }
Run Code Online (Sandbox Code Playgroud)
["68656c6c6f"].pack("H*") #=> "hello"
Run Code Online (Sandbox Code Playgroud)
看看Array的文档,特别是pack和unpack方法.
| 归档时间: |
|
| 查看次数: |
4471 次 |
| 最近记录: |