Ruby single and double quotes

后端 未结 6 1000
情话喂你
情话喂你 2020-11-30 15:01

I\'ve recently been coding in Ruby and have come from Python, where single and double quotes made no difference to how the code worked as far as I know.

I moved to R

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 15:43

    In the string interpolation concept, the essential difference between using single or double quotes is that double quotes allow for escape sequences while single quotes do not.

    Let's take an example:

    name = "Mike"
    puts "Hello #{name} \n How are you?"
    

    The above ruby code with string interpolation will interpolate the variable called name which is written inside brackets with its original value which is Mike. And it will also print the string How are you? in a separate line since we already placed an escape sequence there.

    Output:

    Hello Mike 
      How are you?
    

    If you do the same with single quotes, it will treat the entire string as a text and it will print as it is including the escape sequence as well.

    name = Mike'
    puts 'Hello #{name} \n How are you'?
    

    Output:

    Hello #{name} \n How are you?
    

提交回复
热议问题