Additional Ruby Literals

1 Min. Read
Dec 9, 2019

Ruby literals

In computer science, literal refers to a notation for representing a fixed value in source code. Generally, literals are used to initialize variables like 5 is an integer literal, “apple” is a string literal. Similarly, some of the uncommon literals in Ruby are as follows.

Rational literal

Rational means irreducible fraction number. There is a rational class in Ruby. This can be used by the help of suffix “r” in some numeric values. Additionally, ‘to_r’ function also converts a decimal number into corresponding fraction. You can perform addition, subtraction, multiplication, division etc on the fraction directly using ‘r’ suffix. Lets look at an example;

1
2
3
4
1/5r #1/5
(1/5r).class #Rational
1.5.to_r #3/2
1/5r + 2/3r #13/15

Complex literal

Complex number refers to a number that consist of a real and imaginary part. In Ruby, complex numbers can also be used via literal notation. For this we use ‘to_c’ method or ‘i’ suffix to a complex number. This is not generally used by programmers but is useful in dealing with wave functions, scientific calculations etc.

1
2
3
4
2i  #(0+2i)
2+2i  #2+2i
2+0i  #2+0i
(2.1-1.1i)  #(2.1-1.1i)

String percent literal

Ruby has multiple options to create strings. It can be done using single and double quotes. Using ‘%Q’ or just ‘%’ behaves as double quotation and ‘%q’ behaves as single quotation.

1
2
3
4
5
 %Q(hello how are)  #"hello how are"
 %q(hello how are)  #"hello how are"
 %(hello how are)  #"hello how are"
 %(#{2+3})  #5
 %q(#{2+3})  # "\#{2+3}"

Character literal

Ruby doesnot have a separate character class like string but it does have a “?” prefixed literal to create single character string. It works for ASCII characters, escape sequences and unicode characters/symbols.

1
2
3
?a # "a"
?!  # "!"
?\n # "\n"

Endless Range

Ruby also allows for endless range literal.

1
2
even_no=(0..).map { |n| print(n * 2) }
even_no.first(3).sum  #6

Summary

Ruby programming consists of many literals that helps programmers to perform their work faster. In addition, we have got you some of the uncommon literals in Ruby that may come in handy at uncommon situations.