Table of contents
1.
Introduction
2.
What are Literals?
2.1.
Booleans and nil
2.2.
Numbers
2.3.
Strings
2.4.
Symbols
2.5.
Array
2.6.
Hashes
2.7.
Range
2.8.
Regular Expression
3.
Keyword Literals
4.
Frequently Asked Questions
4.1.
What are Keywords in ruby?
4.2.
What is the use of Range in Ruby?
4.3.
What is a nested hash?
4.4.
In Ruby, how do you append to a string?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Literals and Keyword Literals in ruby

Author SAURABH ANAND
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article we will learn about the various concept of literals and keyword literals in ruby, we will also go through various examples of the same. We will see how Literals and Keyword Literals in ruby are the same or different from any other programming language. 

Literals are values such as 1.0, 'hello world', and [] that are embedded directly into your program text. Whereas, Certain Ruby keywords are primary expressions and can be considered keyword literals.

So, let’s get into the details of the literals in ruby.

What are Literals?

The constant values assigned to the constant variables are known as literals. Literals, we can say, represent fixed values that cannot be changed. It has memory as well, but no variables with references.

For example:

Const int =12

Now let’s get started with the various types of Literals and Keyword Literals in ruby.

Booleans and nil

Both nil and false are false values. In conditional statements, nil is used to represent "no value" or "unknown," but it evaluates to false.

True is a valid value. In conditional statements, all objects except nil and false evaluate to true. (The constants TRUE, FALSE, and NIL are also available, but the lowercase literal forms are preferable.)

# Code for Boolean literals
puts(3+6==9); # returns true
puts(3+13!=18); # returns true
puts(3+134==nil); # return false
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

true
true
false

Numbers

Integers of any size can be written as follows:

1234

1_234

The value of these integers is the same: 1,234. The underscore could be used to improve human reading. An underscore can be used anywhere in the number.

The following is an example of how to write floating-point numbers:

12.34

1234e-2

1.234E1

The value of these integers is the same: 12.34. In floating-point numbers, underscores are also acceptable.

To write integers in decimal, hexadecimal, octal, or binary formats, you can use a specific prefix. Use a 0d prefix for decimal numbers, a 0x prefix for hexadecimal numbers, a 0 or 0o prefix for octal numbers, and a 0b prefix for binary numbers. The number's alphabetic component is not case-sensitive.

Examples:

0d170, 0D170, 0xaa, 0xAa, 0xAA, 0Xaa, 0XAa, 0XaA, 0252, 0o252, 0O252, 0b10101010, 0B10101010

The decimal value of all of these numbers is 170. For readability, you can use an underscore like you can with integers and floats.

#Code to represent Numbers in Ruby
puts("400+2_00+30_0=#{400+2_00+30_0}");
puts("hexa-#{0xba}");
puts("octal-#{0o232}" );
puts("decimal-#{ 0d470}");
puts("binary-#{ 0b1110}");
puts("Float-#{1.234E2}");
puts("hexa-#{ba}"); # error
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

400+2_00+30_0=900
hexa-186
octal-154
decimal-470
binary-14
Float-123.4
main.rb:7:in `<main>': undefined local variable or method `ba' for main:Object (NameError)

Strings

It is identical to Python. The string can be stated using either "" or ", where "" permits the insertion of the escaped characters.

The most common way of writing strings in Ruby  is using ":

For example;

"string in ruby."

The string may be many lines long, but it must not contain internal " :

For example;

"Quoted string: \".  As we can see, it is escaped"

Escaped characters like \n for newline, \t for tab, etc. are permitted in double-quote strings.

Using #{...}, double-quote strings enable interpolation of other values:

Any phrase may be inserted inside the interpolated area, however, for readability, it is preferable to keep the expression concise.

#code for strings in Ruby
puts( "Twenty multiply three is Six : #{20 * 3}")
puts("Thor\nLove\nand\nthunder");
puts('Will\nrelease\nsoon\n...')
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Twenty multiply three is Six : 60
Thor
Love
and
thunder
Will\nrelease\nsoon\n…

Symbols

Inside the interpreter, a symbol in Ruby corresponds to a name. Symbols are inserted into the Ruby interpreter and are never destroyed. So, if they are created in large quantities or are never released, it affects the size of the interpreter.

We can use a colon to refer to a symbol:

:ruby symbol.

By using interpolation, we can also produce symbolic keys:

#code for symbols in Ruby
puts(:":my_id--->#{23+1_5}")
You can also try this code with Online Ruby Compiler
Run Code


Output:

:my_id--->38

Array

Arrays are collections of things generated with the '[' and ']' operators.

# Ruby Code for Array Demo
state = ['UP', 'Bihar', 'Hariyana', 'MP', 'Jharkhand']
puts(state[0])
puts(state[2]) 
puts("\n")
# Like pythin Negative indices are counted from the end of array
print("Negative Index:", state[-3], "\n\n")
  
# [start_from, count_of_array]
puts("[start, count]:", state[0, 3], "\n")
  
# Using ranges.
# as range size exceeded it prints till full length
puts("Using range:", state[0..7])
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

UP
Hariyana

Negative Index:Hariyana

[start, count]:
UP
Bihar
Hariyana

Using range:
UP
Bihar
Hariyana
MP
Jharkhand

Hashes

Like python, we can generate a hash using symbol keys because they are unchangeable once created and can be used as ideal keys. It is represented as {key:value}.

# Code for hashes in Ruby

# Create new hash in Ruby
hash_1 = Hash.new

# Another way of creating hash
hash_2 = {}

# Initializing values and keys
hash_1 = {"peter" => 200, "tony" => 400, "natasha" => 300}

# Initializing values and keys with symbol keys
hash_2 = {peter:1, natasha:2}
print(hash_1.keys, "\n")
print(hash_2.keys, "\n")
for i in hash_2.keys do


# : Should be used while checking before
# its a part of the symbol key
if i==:peter


# Print the value and key
print(i, "=>", hash_2[i], "\n")
end
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

["peter", "tony", "natasha"]
[:peter, :natasha]
peter=>1
You can also try this code with Online Ruby Compiler
Run Code

Range

It is equivalent to the one found in the Python range (). prints any value that could exist between the specified bounds, including the boundary value. It is represented as range1..range2

#code for ranges in Ruby
for i in 7..12 do
puts(i)
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

7
8
9
10
11
12

Regular Expression

A regular expression is a unique string of characters that uses specific syntax and a pattern to match or find other strings or groups of strings.

A pattern between slashes or between random delimiters followed by % r is referred to as a regular expression literal.

Syntax:

/pattern/

/pattern/im # here option can be specified

%r!/usr/local! # general delimited regular expression

#Code for regular expression
line_1 = "tony is better than peter";
line_2 = "peter is smart too";
if ( line_1 =~ /peter(.*)/ )
puts "yes, peter is in line1"
end
if ( line_2 =~ /tony(.*)/ )
puts "yes, tony is in line2"


end
You can also try this code with Online Ruby Compiler
Run Code

Output:

yes, peter is in line1

Keyword Literals

In Ruby, specialized forms of variable reference are known as keyword literals. Let’s look at some of those keyword literals.

  • nil: Evaluates to the nil value, of class NilClass.
     
  • true: Evaluates to the singleton instance of class TrueClass, an object that represents the Boolean value true.
     
  • false: Evaluates to the singleton instance of class FalseClass, an object that represents the Boolean value false.
     
  • self: Evaluate the current object. 
     
  • __FILE__:  Evaluates to a string that names the file that the Ruby interpreter is executing. This can be useful in error messages.
     
  • __LINE__: Evaluates to an integer that specifies the line number within __FILE__ of the current line of code.
     
  • __ENCODING__: Evaluate to an Encoding object that specifies the encoding of the current file.

Frequently Asked Questions

What are Keywords in ruby?

Keywords in ruby are nothing but reserved words used for some specific internal process or represent some predefined actions.No variable, Object, or constant could be named a keyword.

What is the use of Range in Ruby?

Ranges are most commonly used to express a series. Sequences have a beginning, an end, and a method for producing subsequent values in the sequence.

What is a nested hash?

We can use nested hashes to group or associate the data we're working with even more. They assist us in dealing with scenarios in which a category or piece of data is linked to a collection of values rather than a single discrete value.

In Ruby, how do you append to a string?

To append a string to another, use the + operator. 

Eg. a + b + c creates a new string.

Conclusion

In this article, we have extensively discussed the concept of the Literals and Keyword Literals in ruby. We started with the introduction of Keyword Literals, kinds of Literals and Keyword Literals in ruby, and also discussed codes for better understanding of these literals

After reading about the Literals and Keyword Literals in ruby, are you not feeling excited to read/explore more articles on the topic of ruby? Don't worry; Coding Ninjas has you covered. To learn, see Hashes in RubyObject References in Ruby, and Freezing Objects in Ruby.

 You may also consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Thank you image
Live masterclass