From c166d9e0ed6df6dcf954f18f2443b64679713c71 Mon Sep 17 00:00:00 2001 From: Philip Li Date: Wed, 24 Jul 2024 20:16:21 +0800 Subject: [PATCH] lib/string_ext.rb: add unicode_escape Signed-off-by: Philip Li --- lib/string_ext.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/string_ext.rb b/lib/string_ext.rb index 79c1f827a..16f0eae71 100755 --- a/lib/string_ext.rb +++ b/lib/string_ext.rb @@ -31,4 +31,16 @@ def numeric? def uncolorize gsub(/\e\[(\d+)?(;\d+)?(;\d+)?m/, '').gsub(/\e\[K/, '') end + + def unicode_escape + str = chars.map do |char| + if char.ascii_only? + char + else + char.codepoints.map { |cp| "\\u#{cp.to_s(16).rjust(4, '0')}" }.join + end + end + + str.join + end end