Skip to content

Commit

Permalink
feature: removing nonprintable characters
Browse files Browse the repository at this point in the history
  • Loading branch information
spyderdfx committed Jun 1, 2018
1 parent 7a7fa7d commit a7703c5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/string_tools/core_ext/string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,30 @@ def mb_downcase
mb_chars.downcase.to_s
end

# Public: returns copy of string with all non-printable characters removed
#
# Examples
#
# "q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable
# # => "qwerty"
#
# Returns String
def remove_nonprintable
gsub(/[^[:print:]]/i, '')
end

# Public: removes all non-printable characters from string
#
# Examples
#
# "q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable!
# # => "qwerty"
#
# Returns String
def remove_nonprintable!
replace(remove_nonprintable)
end

private

def surround_with_ansi(ascii_seq)
Expand Down
12 changes: 12 additions & 0 deletions spec/string_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,16 @@
describe '#mb_downcase' do
it { expect("Кириллица".mb_downcase).to eq("кириллица") }
end

describe '#remove_nonprintable' do
let(:string) { "\uFDD1string\uFFFE \uFFFFwith\uFDEF weird characters\uFDD0" }

it { expect(string.remove_nonprintable).to eq 'string with weird characters' }
end

describe '#remove_nonprintable!' do
let(:string) { "\uFDD1string\uFFFE \uFFFFwith\uFDEF weird characters\uFDD0" }

it { expect { string.remove_nonprintable! }.to change { string }.to('string with weird characters') }
end
end

0 comments on commit a7703c5

Please sign in to comment.