Reputation: 3
How can I append the string '\x'
to a number in Ruby? I have tried '\\x'
but it's not working.
Upvotes: 0
Views: 1569
Reputation: 52326
If you're using a single-quoted string for '\x'
then you may already have what you want. When Ruby (or to be more accurate, IRB) prints a string with a literal backslash it shows it escaped by default, which is how #p
behaves (that's what IRB uses to show results). But the string may only have one blackslash as desired.
num = 123
s = '%d\x' % num #=> "123\\x" (using the short-hand form for sprintf)
print s #=> 123\x
p s #=> "123\\x"
puts '%d\x' % num #=> 123\x - what the string actually contains
puts num.to_s + '\x'
Note that in Ruby single quoted string literals undergo a lot less substitution than double-quoted ones.
Upvotes: 0
Reputation: 66867
Without context it's hard to know what you are trying to achieve. Here are some ways (if you really want to append):
"%d\\x" % num
"#{num}\\x"
If you are trying to output hex numbers, this is good:
"\\x%s" % num.to_s(16)
Upvotes: 0
Reputation: 5832
Probably something like:
my_string = 'foo 123 456 bar'
my_string.gsub(/(\d+)/, '\\x\1') # "foo \\x123 \\x456 bar"
Upvotes: 1