What does #{…} mean?

前端 未结 3 1988
南方客
南方客 2020-12-12 02:12

Such as in the following code from Why\'s Poignant Guide:

def wipe_mutterings_from( sentence ) 
     unless sentence.respond_to? :include?
         raise Arg         


        
3条回答
  •  醉梦人生
    2020-12-12 02:36

    In a Ruby double-quoted string—which includes string literals like s = "…" and s = %Q{ ... } and s = <—the syntax #{ … } is used for "string interpolation", inserting dynamic content into the string. For example:

    i = 42
    s = "I have #{ i } cats!"
    #=> "I have 42 cats!"
    

    It is equivalent to (but more convenient and efficient than) using string concatenation along with explicit calls to to_s:

    i = 42
    s= "I have " + i.to_s + " cats!"
    #=> "I have 42 cats!"
    

    You can place arbitrary code inside the region, including multiple expressions on multiple lines. The final result of evaluating the code has to_s called on it to ensure that it is a string value:

    "I've seen #{
      i = 10
      5.times{ i+=1 }
      i*2
    } weasels in my life"
    #=> "I've seen 30 weasels in my life"
    
    [4,3,2,1,"no"].each do |legs|
      puts "The frog has #{legs} leg#{:s if legs!=1}"
    end
    #=> The frog has 4 legs
    #=> The frog has 3 legs
    #=> The frog has 2 legs
    #=> The frog has 1 leg
    #=> The frog has no legs
    

    Note that this has no effect inside single-quoted strings:

    s = "The answer is #{6*7}" #=> "The answer is 42"
    s = 'The answer is #{6*7}' #=> "The answer is #{6*7}"
    
    s = %Q[The answer is #{ 6*7 }] #=> "The answer is 42"
    s = %q[The answer is #{ 6*7 }] #=> "The answer is #{6*7}"
    
    s = < "The answer is 42\n"
    
    s = <<'ENDSTRING'
    The answer is #{6*7}
    ENDSTRING
    #=> "The answer is #{6*7}\n"
    

    For convenience, the {} characters for string interpolation are optional if you want to insert just the value of an instance variable (@foo), global variable ($foo), or class variable (@@foo):

    @cats = 17
    s1 = "There are #{@cats} cats" #=> "There are 17 cats"
    s2 = "There are #@cats cats"   #=> "There are 17 cats"
    

提交回复
热议问题