Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of #{ } in Ruby?

Tags:

string

ruby

The operation #{ } appears to be so fundamental that my Ruby book completely skips its definition. Can someone provide an explanation?

like image 946
Toaster Avatar asked Jun 03 '12 09:06

Toaster


People also ask

Is Miscare a word?

Noun (UNCOUNTABLE)Faulty or improper care.

Is definitionally a word?

Adverb. In a definitional manner; as a definition.


2 Answers

Why This Is a Good Question

This is a tough question to Google for unless you know the right search terms. The #{} operator technically performs expression substitution inside a string literal.

The Answer

The #{} literal is the operator used for interpolation inside double-quoted strings the same way that the backticks or $() construct would be used in Bash. From a practical point of view, the expression inside the literal is evaluated, and then the entire #{} expression (including both the operator and the expression it contains) is replaced in situ with the result.

Related Links

  • http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#string
  • http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
  • http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Interpolation
  • Ruby (on Rails) syntax
like image 151
Todd A. Jacobs Avatar answered Oct 15 '22 12:10

Todd A. Jacobs


It allows you to put Ruby code within a string. So:

"three plus three is #{3+3}" 

Would output:

"three plus three is 6"

It's commonly used to insert variable values into strings without having to mess around with string concatenation:

"Your username is #{user}" 
like image 23
Sean Avatar answered Oct 15 '22 12:10

Sean