Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在尝试将字符串中的所有数字转换为十六进制。我试过这段代码:
str.gsub(/(\d+)/, '\1'.to_i.to_s(16))
但这会替换每个数字,0因为它修改的是字符串'\1'而不是替换的数字\1。
0
'\1'
\1
我怎样才能正确使用gsub?
gsub
String#gsub接受一个块。块的返回值用作替换值:
String#gsub
>> str = '100 200' => "100 200" >> str.gsub(/\d+/) { |x| x.to_i.to_s(16) } => "64 c8"