Page Content

Tutorials

What Are Literals In Ruby Explained With Code Examples

Literals in Ruby

Literals in Ruby are values that show up right in the source code of your program. They are the most basic types of expressions since they convey values directly without requiring additional calculations. A program is broken down into tokens by the Ruby interpreter during parsing, and literals are one kind of token. The values true, false, and nil, as well as simple numeric literals, are all objects in Ruby.

Here is a description of the many kinds of literals in Ruby along with some sample code:

Numeric Literals

Numerical literals are used to express numerical quantities.

Integer Literals: These are numerical sequences. The interpreter ignores underscores (_), which can be added to integer literals for readability.

  • Different bases can be used to express integers:
    • Decimal (base 10): Standard digits.
    • Hexadecimal (base 16): Begin with 0x or 0X (e.g., 0xFF).
    • Binary (base 2): Begin with 0b or 0B (e.g., 0b1010).
    • Octal (base 8): Begin with 0 (e.g., 0377).
  • A minus symbol appears before a negative number.
  • Fixnum objects are values that fall inside the Fixnum class range; variables outside of this range support arbitrary size and are Bignum objects. The term “immediate values” refers to fixnum objects in Ruby’s implementation.

Floating-Point Literals: They are actual numbers. They consist of a decimal point, one or more digits, an optional exponent (such as e or E), an optional sign, and further digits. Underscores are permitted as well. The decimal point must be preceded and followed by digits in Ruby (0.1 instead of.1).

String Literals

String literals, which belong to the String class, are objects that represent character sequences.

Single-Quoted String Literals: String literals enclosed in single quotes (‘) are known as single-quoted strings.

  • The only escape sequences they offer are \' for a single quotation and \ for a single backslash. Backslashes that are not followed by’or \ are taken literally, as are all other characters.

Double-Quoted String Literals: Double quote marks (“) are used to indicate borders.

  • They are more flexible, supporting numerous backslash escape sequences like \n (newline), \t (tab), \" (double quote), \a (bell/alert), \b (backspace), \r (carriage return), \f (form feed), \e (escape), and hexadecimal/octal byte representations (\xnn, \nnn).
  • They also support string interpolation, allowing arbitrary Ruby expressions to be embedded using #{expression}. If the expression is a global, instance, or class variable, the curly braces can be omitted (e.g., "$salutation" for $salutation).
  • If line terminators are not escaped with a backslash, they form part of the string, and double-quoted strings can span many lines.

“Here Documents”: Utilized when dealing with lengthy string literals, particularly when handling quotes and special characters becomes difficult. An identifier or a string that serves as the final delimiter comes just after the initial << or <<-. Up until the delimiter shows up on a line by itself, the string content starts on the following line.

  • The document in question adheres to single-quoted string rules if the delimiter is single-quoted; if not, it follows double-quoted standards.

Percent (%) Notation: For strings, arrays, and regular expressions, a generalised quotation syntax.

  • %q acts like single quotes.
  • %Q (or just %) acts like double quotes.
  • The character immediately following q or Q (or %) becomes the delimiter. If it’s a paired character ((, [, {, <), it expects a matching closing delimiter.

Character Literals: A single character in Ruby can be denoted by putting a question mark before it (?A, for example).

  • Character literals in Ruby 1.8 evaluated to the ASCII integer encoding (?A was 65, for example).
  • The string “a” is the result of?a evaluation in Ruby 1.9 and later. Control characters like?\C-x or escape sequences like?\t can also be included.

You can also read What Is Mean By Comments In Ruby With Code Examples

Array Literals

Integer-indexed, ordered collections of objects are called array literals. They appear as a list of items enclosed in square brackets ([]) and separated by commas. A trailing comma is permitted, and array elements may be any expression.

There are specific syntaxes for arrays of strings:

  • An array of words (space-separated tokens) is produced by %w; no string interpolation takes place.
  • Although it also generates an array of words, %W replaces each word with a double-quoted text.

Code Examples:

puts [92-94]                  # Array of integers: [92-94] 
puts [[92, 93], [94, 95], [96]]        # Array of nested arrays 
x = 10; y = 20
puts [x + y, x - y, x * y]      # Array elements can be expressions 

puts []                         # An empty array 
words = %w[this is a test]      # Array of strings: ["this", "is", "a", "test"] 
white_chars = %W(\s \t \r \n)   # Array of strings with interpolation: [" ", "\t", "\r", "\n"] 

Output

-2
92
93
94
95
96
30
-10
200

Hash Literals

Hash literals, like dictionaries, are collections of key-value pairs. Curly braces ({}) contain a list of key => value pairs that are separated by commas.

Symbol objects’ immutability and uniqueness make them frequently more effective hash keys than String objects.

Code Examples:

puts ({ "one" => 1, "two" => 2, "three" => 3 }) # Hash with string keys 

puts ({ :one => 1, :two => 2, :three => 3 })   # Hash with symbol keys 

# Ruby 1.9+ shortcut for symbol keys
puts ({ one: 1, two: 2, three: 3 })

Output

{"one" => 1, "two" => 2, "three" => 3}
{one: 1, two: 2, three: 3}
{one: 1, two: 2, three: 3}

You can also read What Are Variables In Ruby With The Practical Code Examples

Range Literals

A range literal is a set of values that connects a start and an end point. To write them, put two or three dots in between the beginning and ending values.

Inclusive Range (..): Includes the end value.

Exclusive Range (…): Excludes the end value.

Code Examples:

puts (1..10)      # Inclusive range of integers (1 to 10, including 10) 

puts (1.0...10.0) # Exclusive range of floats (1.0 up to, but not including, 10.0)

Output

1..10
1.0...10.0

Symbol Literals

In Ruby, symbols are immutable, interned strings that are mostly used for names, such as identifiers, hash keys, or method names. They can be represented as colon-prefixed identifiers (like :name) or as a colon before a string literal (like :”my variable”). Symbol objects are “immediate values” identical to Fixnum objects.

Code Examples:

puts :my_symbol           # A simple symbol 
puts :"another symbol"    # Symbol from a string literal with spaces 
name = "dynamic"
puts :"#{name}_symbol"    # Symbol with interpolation 

Output

my_symbol
another symbol
dynamic_symbol

Regular Expression Literals

Regular expression literals, often known as Regexp objects, specify textual patterns for string matching and search. They are distinguished by the forward slash (/pattern/).

  • The last slash may be followed by optional flag characters (e.g., i for case-insensitive, m for multiline).
  • The notation %r{pattern} can also be applied.

Code Examples:

puts /Ruby?/              # Matches "Rub" followed by an optional "y" 

puts /ruby?/i             # Case-insensitive match for "ruby" or "RUB" 

puts %r{https?://\S+}i    # Regex using %r notation for URLs (case-insensitive)

Output

(?-mix:Ruby?)
(?i-mx:ruby?)
(?i-mx:https?:\/\/\S+)

Keyword Literals

Some Ruby keywords are also main expressions, and they can be thought of as specialised variable references or keyword literals.

Code Examples:

puts true                 # Evaluates to the TrueClass singleton instance 
puts false                # Evaluates to the FalseClass singleton instance 
puts nil                  # Evaluates to the NilClass singleton instance 
puts self                 # Evaluates to the current object 
puts __FILE__             # Evaluates to the current filename as a string 
puts __LINE__             # Evaluates to the current line number as an integer 
# puts __ENCODING__       # Evaluates to the Encoding object for the current file (Ruby 1.9+) 

Output

true
false

main
/tmp/kHTjljAawJ/main.rb
6

You can also read Constants In Ruby: What They Are, It’s Scope And Access

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index