Codectionary / Developer documentation / Ruby

Ruby Variables & Strings

Ruby uses local variables without a declaration keyword. Strings can be enclosed in single or double quotes; double-quoted strings support interpolation with #{...}.

Syntax

name = "Ada"
puts "Hello, #{name}"

Breaking down the syntax

name = value
Assigns a value to a local name.
#{...}
Inserts an expression into a double-quoted string.
puts
Writes a value with a newline.

How it works

Ruby variable names refer to objects. Assigning a new value can make the same local name refer to a different object.

Assign

Bind a local name.

Build text

Interpolate values into a string.

Output

Print the message.

Examples

A small working example

Follow the values through this example, then change one input.

name = "Ada"
lessons = 3
puts "#{name} completed #{lessons} lessons"
  1. Two local names receive values.
  2. Double quotes enable interpolation.
  3. puts writes the constructed message.

Interpolating a string

A small, runnable example of this syntax.

name = "Ada"
visits = 3
puts "#{name} has #{visits} visits."

Best practices

  • Use meaningful local-variable names and prefer interpolation instead of manually concatenating values into strings.
  • Keep examples small while learning, then combine the idea with a real project.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

When should I use this?

Give meaningful names to values in a script or method.

Common mistakes

A common trap

An uppercase initial letter declares a constant name rather than a local variable.

Incorrect

Name = "Ada" # constant, not a local variable

Corrected

name = "Ada" # local variable

Compare approaches

  • Local variable: Use a lowercase or underscore initial character.
  • Instance variable: Use @name for state belonging to an object.

Explore deeper

Assignment and object mutation differ

Reassigning a local name changes what that name refers to. Mutating a shared object can affect other references to the same object.

Specifications & further reading