mrwnt10
mrwnt10

Reputation: 1425

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

Upvotes: 2

Views: 1387

Answers (3)

Phrogz
Phrogz

Reputation: 303559

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"

Upvotes: 6

Arup Rakshit
Arup Rakshit

Reputation: 118299

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

Upvotes: 4

ddavison
ddavison

Reputation: 29102

#{} 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

Upvotes: 1

Related Questions