rubystringbyebug

Why does include? for Ruby return false?


I have the following Ruby fragment from a byebug session:

(byebug) target_name
"foo/"
(byebug) target_name.class
String
(byebug) target_name.include?('/')
false
(byebug) "foo/".include?('/')
true

Why does the include? method return false as / is part of foo/?

Ruby version:

ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-linux]

Solution

  • It is possible that target_string contains some non-ascii characters.

    For example compare:

    irb(main):019:0>> str = "foo/"
    => "foo/"
    irb(main):020:0> str.ascii_only?
    => true
    irb(main):021:0> str.include?("/")
    => true
    

    and

    irb(main):022:0> str = "foo\xe2\x88\x95"
    => "foo∕"
    irb(main):023:0> str.ascii_only?
    => false
    irb(main):024:0> str.include?("/")
    => false
    

    In the latter example the string contains the "forward slash" U+2215 character encoded as utf-8 bytes.

    Depending on your specific use case, you could e.g. convert the string to ascii and blindly replace any undefined or invalid character with a /.

    str.encode("ascii", "utf-8", replace: "/")
    

    Look at the #encode method for more options.