Triple single quote vs triple double quote in Ruby

后端 未结 4 1094
天涯浪人
天涯浪人 2021-01-06 08:13

Why might you use \'\'\' instead of \"\"\", as in Learn Ruby the Hard Way, Chapter 10 Study Drills?

4条回答
  •  孤街浪徒
    2021-01-06 08:51

    In Ruby """ supports interpolation, ''' does not.

    Rubyists use triple quotes for multi-line strings (similar to 'heredocs').

    You could just as easily use one of these characters.

    Just like normal strings the double quotes will allow you to use variables inside of your strings (also known as 'interpolation').

    Save this to a file called multiline_example.rb and run it:

    interpolation = "(but this one can use interpolation)"
    
    single = '''
    This is a multi-line string.
    '''
    
    double = """
    This is also a multi-line string #{interpolation}.
    """
    
    puts single
    puts double
    

    This is the output:

    $ ruby multiline_string_example.rb
    
    This is a multi-line string.
    
    This is also a multi-line string (but this one can use interpolation).
    
    $
    

    Now try it the other way around:

    nope = "(this will never get shown)"
    
    single = '''
    This is a multi-line string #{nope}.
    '''
    
    double = """
    This is also a multi-line string.
    """
    
    puts single
    puts double
    

    You'll get this output:

    $ ruby multiline_example.rb
    
    This is a multi-line string #{nope}.
    
    This is also a multi-line string.
    
    $
    

    Note that in both examples you got some extra newlines in your output. That's because multiline strings keep any newlines inside them, and puts adds a newline to every string.

提交回复
热议问题