Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string length "\\\'"

Tags:

string

ruby

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
like image 211
Ask and Learn Avatar asked Jun 12 '26 02:06

Ask and Learn


2 Answers

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: \'
like image 184
Andrew Marshall Avatar answered Jun 15 '26 03:06

Andrew Marshall


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 }
# >> \
# >> '
like image 22
Arup Rakshit Avatar answered Jun 15 '26 02:06

Arup Rakshit