Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

ruby - What does #{...} mean?

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

def wipe_mutterings_from( sentence ) 
     unless sentence.respond_to? :include?
         raise ArgumentError, "cannot wipe mutterings from a #{ sentence.class }"
     end
     while sentence.include? '('
         open = sentence.index( '(' )
         close = sentence.index( ')', open )
         sentence[open..close] = '' if close
     end
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In a Ruby double-quoted string—which includes string literals like s = "…" and s = %Q{ ... } and s = <<ENDCODE—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 = <<ENDSTRING
The answer is #{6*7}
ENDSTRING
#=> "The answer is 42
"

s = <<'ENDSTRING'
The answer is #{6*7}
ENDSTRING
#=> "The answer is #{6*7}
"

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...