Adding Variables into String in Ruby

You can always add variable into string in Ruby by concatenating variable with string via #{} notation. Example of such enclosure is the following use case

my-string = “adding string”

my-integer = 10

“My original string and additional #{my-string}. And my number is #{my-integer}”.

It is important to note in Ruby variable and string concatenation happen regardless of the data type of the variable. In the example above, you can see that my-integer was easily added to a string without any errors you may see with other languages that require you to perform casting or conversions.

Here is more complex example of such concatenation of Ruby object with the string.

%{Here is #{
class InstantClass
 def bar
  "some text"
 end
end }.}

In case you need to escape string interpolation, you can always escape it using back slash or adding single quotes around it.

“\#{my-string}” or ‘#{my-string}’

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…