Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 3 / 68

Working with Variables

In this lesson you will learn the basics of variables in Ruby and string interpolation, and how to assemble readable text. This is for anyone searching for "Ruby variables how to use" or "Ruby string interpolation".

A variable is like a labelled box that stores a value under a name. In Ruby you create one simply with name = value. Writing #{variableName} inside a string embeds the value (string interpolation).

The sample code declares name and age, then assembles a message with interpolation in "Hello, #{name}! You are #{age} years old". Compared with joining strings using + as other languages do, it reads noticeably better.

A common stumbling block for beginners is which kind of quote allows interpolation. Double quotes enable it and single quotes disable it - with single quotes, #{name} is printed literally as text.

Interpolation #{} lets you drop a calculation or a variable straight into a string, which keeps the code very readable. Getting comfortable with it is a first step towards writing idiomatic Ruby.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)