2

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
sawa
  • 165,429
  • 45
  • 277
  • 381
mrwnt10
  • 1,234
  • 1
  • 17
  • 28

3 Answers3

6

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\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"
Phrogz
  • 296,393
  • 112
  • 651
  • 745
4

"#{}" means in Ruby string interpolation.See Here for too many answers.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • 2
    and string interpolation means that the content of the variable/expression is placed into the embedding string at that location. – mnagel Aug 06 '13 at 20:39
1

#{} is used for Ruby interpolation. In this example,

this will raise an ArgumentError with the message,

cannot wipe mutterings from a <whatever sentence.class evaluates to>

This is a useful read - String concatenation vs. interpolation in Ruby

Community
  • 1
  • 1
ddavison
  • 28,221
  • 15
  • 85
  • 110