w3resource logo


Ruby tutorials

Ruby Literals

Secondary Nav

Literals

We have already seen literals: every time we type an object directly into Ruby code, we are using a literal. Literals create objects which are used in the program.

Ruby Literals include :

  • Booleans and nil
  • Numbers
  • Strings
  • Symbols
  • Arrays
  • Hashes
  • Ranges
  • Regular Expressions
  • Procs

Booleans and nil

  • nil and false are both false values.
  • nil is used to indicate "no value" or "unknown" but evaluates to false in conditional expressions.
  • true is a true value.
  • All objects except nil and false evaluate to a true value in conditional expressions.

Note : There are also the constants TRUE, FALSE, and NIL, but the lowercase literal forms are preferred.

Numbers

You can write integers of any size as follows :

  • 100
  • 1_00

These numbers have the same value, the underscore may be used to enhance readability for humans. You can place an underscore anywhere in the number. See the following example :

irb(main):001:0> 100
=> 100
irb(main):002:0> 1_00
=> 100
irb(main):003:0> 100 + 1_00
=> 200

You can write the floating numbers in the following ways :

  • 15.34
  • 7234e-2
  • 1.234E1

You may use underscores in floating point numbers as well.

Prefix :

You can use a special prefix to write numbers in decimal, hexadecimal, octal or binary formats.

  • Use a prefix of 0d for decimal numbers
  • Use a prefix of 0x for hexadecimal numbers
  • Use a prefix of 0 or 0o for octal numbers
  • Use a prefix of 0b for binary numbers

Note : The alphabetic component of the number is not case-sensitive.

All the following numbers have the same decimal value, 170.

Examples : decimal numbers

  • 0d170
  • 0D170

Examples : hexadecimal numbers

  • 0xaa
  • 0xAa
  • 0xAA
  • 0Xaa
  • 0XAa
  • 0XaA

Examples : octal numbers

  • 0252
  • 0o252
  • 0O252

Examples : binary numbers

  • 0b10101010
  • 0B10101010

Strings

  • A string expression begins and ends with a double or single-quote mark.
  • The most common way of writing strings is using ".
  • Double-quoted string expressions are subject to backslash notation and interpolation.
  • Double-quote strings allow escaped characters such as \n for newline, \t for the tab, etc.

See the following example :

puts("This is a simple string")
puts("This string has a double quote: \". It is escaped")
puts("Double-quote strings allow escaped characters such as \n for newline, \t for tab, etc.")

Output :

This is a simple string
This string has a double quote: ". It is escaped
Double-quote strings allow escaped characters such as
 for newline,    for tab, etc.

The following table shows the various escape situation :

Escape Sequence Meaning
\n newline (0x0a)
\s space (0x20)
\r carriage return (0x0d)
\t tab (0x09)
\v vertical tab (0x0b)
\f formfeed (0x0c)
\b backspace (0x08)
\a bell/alert (0x07)
\e escape (0x1b)
\nnn character with octal value nnn
\xnn character with hexadecimal value nn
\unnnn Unicode code point U+nnnn (Ruby 1.9 and later)
\cx control-x
\C-x control-x
\M-x meta-x
\M-\C-x meta-control-x
\x character x itself (\" a single quote, for example)

Interpolation

In Ruby Double-quote strings allow interpolation of other values using #{...} :

Example :

puts( "Two multiply three is Six : #{2 * 3}")

Output :

Two multiply three is Six : 6

#{expression} is used to handling string delimiters that appear in the code

The % Notation

You may also create strings using % in Perl style to quote strings.

Example :

puts(%(This is the usage of % string))

Output :

This is the usage of % string

Types of strings in ruby :

Types Description
%i Array of Symbols
%q String
%r Regular Expression
%s Symbol
%w Array of Strings
%x Backtick (capture subshell result)

Here Documents

To write a large block of text you can use a "here document" or "heredoc" where the delimiter itself can be any string. See the following example.

If you are writing a large block of text you may use a “here document” or “heredoc”:

str1 = <<HEREDOC
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of type
and scrambled it to make a type specimen book. It has survived not 
only five centuries, but also the leap into electronic typesetting, 
remaining essentially unchanged. It was popularised in the 1960s 
with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker 
including versions of Lorem Ipsum.
HEREDOC
puts(str1)

Output :

Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of type
and scrambled it to make a type specimen book. It has survived not 
only five centuries, but also the leap into electronic typesetting, 
remaining essentially unchanged. It was popularised in the 1960s 
with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker 
including versions of Lorem Ipsum.

The syntax begins with << and is followed immediately by the delimiter. To end the string, the delimiter appears alone on a line.

Any identifier (uppercase) can be used with a heredoc. You may indent the ending identifier if you place a "-" after <<. See the following example

result = <<-INDENTED_HEREDOC
  Lorem Ipsum is simply dummy text of the printing and typesetting
  industry.
  Lorem Ipsum has been the industry's standard dummy text
  ever since the 1500s, when an unknown printer took a galley of type
  and scrambled it to make a type specimen book.
  INDENTED_HEREDOC
  puts(result)

Output :

Lorem Ipsum is simply dummy text of the printing and typesetting
industry. 

Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of type
and scrambled it to make a type specimen book.

You can use non-alpha-numeric characters in the delimiter, it can be quoted :
Example :

result = <<-"***"
  Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. 
  Lorem Ipsum has been the industry's standard dummy text
  ever since the 1500s, when an unknown printer took a galley of type
  and scrambled it to make a type specimen book.
  ***
  puts(result)

Output :

Lorem Ipsum is simply dummy text of the printing and typesetting
industry. 
Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of type
and scrambled it to make a type specimen book.

A heredoc allows interpolation and escaped characters, though can disable interpolation and escaping using single quotes around the delimiter.
Example :

str1 = <<-HEREDOC
puts( "Two multiply three is Six : #{2 * 3}") HEREDOC
puts(str1)

Output :

puts( "Two multiply three is Six : 6")

If you want to call a method on a heredoc place it after the opening identifier:

expected_result = <<-EXPECTED.chomp 
One plus one is #{1 + 1} EXPECTED

Note : You can open multiple heredocs on the same line, but this can be difficult to read:

Symbols

In Ruby a symbol represents a name inside the interpreter.
Syntax :

:ruby_symbol

You can also create symbols by interpolation :

:"my_id"
puts(:"my_id#{200 + 15}")

Arrays

An array is a collection of objects indexed by a non-negative integer and is created by using the objects between [ and ] :

An array is a collection of objects indexed by a non-negative integer. You can create an array object by writing Array.new, by writing an optional comma-separated list of values inside square brackets, or if the array will only contain string objects, a space-delimited string preceded by %w.

array1 = Array.new
# array2 shorthand for Array.new
array2 = []              
# array3 contains 1, 2, 3
array3 = [1, 2, 2] 
# array4 also contains 1, 2, 3
array4 = %w[1 2 3]

Here are some examples :

my_color = ['Red', 'Black', 'White', 'Green', 'Orange']
puts(my_color[0])
puts(my_color[2])
#negative indices are counted from the end
puts(my_color[-2])
puts('-----------')
#[start, count]
puts(my_color[1,3])
puts('-----------')
#using ranges.
puts(my_color[0..1])

You may place expressions inside the array:

[100, 100 + 100, 100 + 200]
[100, [100 + 100, [100 + 200]]]

See Array for the methods you may use with an array.

Hashes

Hashes are basically the same as arrays, except that a hash not only contains values but also keys pointing to those values. A hash object is created in the following ways :

hash1   = Hash.new
hash2   = {}  
hash3 = {"num1" => 100, "num2" => 200, "num3" => 300

You can create a hash using symbol keys with the following syntax :

{ x: 1, y: 2 }

Ranges

A range represents a subset of all possible values of a type. The range may include or exclude its ending value. You can create a range in the following ways :

# All integers between 0 and 10.
0..10
# All numbers (including non-integers) between 0 and 3, excluding 3.
0.0...3.0
# All characters between 'a' and 'f'.
'a'..'f'

Regular Expressions

A Regular expressions (regexps) is used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals. See the following syntax.

/my regular expression/

The regular expression may be followed by flags which are responsible for matching the behavior of the regular expression. The "x" flag ignore whitespace and comments in the pattern

/my regular expression/x

Interpolation may be used inside regular expressions along with escaped characters.

Procs

A proc can be created with -> :

-> { 2 + 2 }

Calling the above proc will give a result of 4.

You can require arguments for the proc as follows:

->(v) { 2 + v }

This proc will add one to its argument.



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables