Ruby single and double quotes

后端 未结 6 1008
情话喂你
情话喂你 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:39

    In Ruby, double quotes are interpolated, meaning the code in #{} is evaluated as Ruby. Single quotes are treated as literals (meaning the code isn't evaluated).

    var = "hello"
    "#{var} world" #=> "hello world"
    '#{var} world' #=> "#{var} world"
    

    For some extra-special magic, Ruby also offers another way to create strings:

    %Q() # behaves like double quotes
    %q() # behaves like single quotes
    

    For example:

    %Q(#{var} world) #=> "hello world"
    %q(#{var} world) #=> "#{var} world"
    

提交回复
热议问题