0

I just faced this question in interview. Is it possible to escape character within single quotes in ruby?

The confusion is in following code

puts '\\'   # Output: \
puts '\n'   # Output: \n

It seems that backword slash is escaped but the newline character isn't.

I am aware of this question but I am not asking about difference between single and double quote. I am asking about whether it's possible to escape characters in single quotes or not? And why only backslash is allowed to escape?

Community
  • 1
  • 1
Hardik
  • 3,815
  • 3
  • 35
  • 45
  • What is the expected form? – sawa Aug 26 '14 at 06:20
  • @sawa Most of the books/references says that diff b/w double quote and single quote is that there is no character escaping in single quotes... but it seems that '\\' is escaped. so most of the references are wrong I guess... – Hardik Aug 26 '14 at 06:26

1 Answers1

3

The only characters that needs to be escaped in a single quoted string are '\\' (for backslash \) and '\'' (for single quote ' itself).

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • and also '\1', '\2', and so on to call Regexp match array, i believe. – Adrian Aug 26 '14 at 06:13
  • thanx for the answer... So there is no other way to escape other characters in single quotes? – Hardik Aug 26 '14 at 06:23
  • 1
    @UandI I don't think so. – Yu Hao Aug 26 '14 at 06:28
  • @sawa what I meant was, you also use \ to get the first, second, ..match string in a sub, gsub, and maybe tr also when you replace the match given in the first argument. – Adrian Aug 26 '14 at 08:12
  • 1
    @styd This question/answer is about what needs to be escaped. It is not about how a backslash is used (other than for escaping). Your comment is out of the context. And your wording "also" contradicts with your latter comment. – sawa Aug 26 '14 at 08:18