File: ascii_only.rb

package info (click to toggle)
ruby-powerpack 0.1.1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 492 kB
  • sloc: ruby: 819; makefile: 3
file content (42 lines) | stat: -rw-r--r-- 1,341 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# encoding: utf-8

class String
  # Return a copy of string with ASCII characters only
  # Source: http://stackoverflow.com/questions/1268289/how-to-get-rid-of-non-ascii-characters-in-ruby
  #
  # @return [String] a copy of string with ASCII characters only
  #
  # @example
  #   'abc'.ascii_only #=> 'abc'
  #
  # @example
  #   '中文123'.ascii_only #=> '123'
  unless String.method_defined? :ascii_only
    def ascii_only
      dup.ascii_only!
    end
  end

  # Modify self and keep ASCII characters only
  # Returns the string even if no changes were made.
  # Source: http://stackoverflow.com/questions/1268289/how-to-get-rid-of-non-ascii-characters-in-ruby
  #
  # @return [String] The result string
  #
  # @example
  #   'abc'.ascii_only! #=> 'abc'
  #
  # @example
  #   '中文123'.ascii_only! #=> '123'
  unless String.method_defined? :ascii_only!
    def ascii_only!
      encoding_options = {
        :invalid                     => :replace,  # Replace invalid byte sequences
        :undef                       => :replace,  # Replace anything not defined in ASCII
        :replace                     => '',        # Use a blank for those replacements
        :UNIVERSAL_NEWLINE_DECORATOR => true       # Always break lines with \n
      }
      self.encode! Encoding.find('ASCII'), encoding_options
    end
  end
end