Why are string.size and string.length 2? I think it should be 3. If the first \ is an escape character, then it should not be printed out. That is what happened to the third \.
string='\\\'' # => "\\'"
string.size # => 2
string.length # => 2
If first
\is escape character then it should not be printed out. That is what happened to 3rd\.
No, because what’s being printed is the result of String#inspect, which escapes for a double-quoted string. Since a ' does not need to be escaped here, no escape character (\) is needed.
I think it should be 3
size/length doesn’t lie, so it is, of course, actually two.
In a single-quoted string, \\ is the single character \, and \' is the single character '. So the resulting string is \'. puts is more useful than inspect since it does not show any escaping, just the literal contents:
puts '\\\''
# prints: \'
Here is the answer :
string='\\\''
string.chars # => ["\\", "'"]
In this case you should use String#chars to see how many and what are the characters are used to compose the string.So the output of string.chars is telling the your string has 2 characters,thus the size is 2.You have 2 characters : one is \ and the other is '. Both of them are escaped by \.
EDIT(as @Andrew Marshall said)
string='\\\''
string.each_char{ |char| puts char }
# >> \
# >> '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With