Lexical Structure in Ruby
Like Human Languages, Computer languages also follow a lexical structure. A source code of the ruby program consists of tokens. While parsing any program, the ruby-interpreter parses the program as a sequence of these tokens. Tokens in ruby include literal, punctuation, comments, identifiers, and keywords. This article introduces you to one type of token, i.e., Literals in ruby. Tokens also include essential information about the characters that comprise the tokens and the whitespace that separates the tokens.
Literals in Ruby
Literals in ruby are any constant value which can assign to a variable. We are using literals in ruby every time we type an object. Or, in simpler terms, Literals in ruby are values that appear directly in Ruby source code. Literals in ruby are the same as literals in any other programming language but with a few adjustments here and there.
These are the following literals in ruby:-
- Booleans and Nill
- Numbers
- Strings
- Symbols
- Ranges
- Arrays
- Hashes
-
Regular Expressions
Looking into each of them in brief down the section
Booleans and Nil
Nil and Boolean False indicate false values, i.e., they have the same behavior. They are boolean constant, and Nil represents unknown or empty, but it does behave similarly to boolean False. True behave similarly to the positive variable. Look for the below code to get more information.
Code:-
# Code Explanation for Boolean literals
puts(12+13==25); # Following expression returns true
puts(12+13!=15); # Following expression returns false
puts(12+13==nil); # Following expression return false

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Numbers
Ruby supports integers of all types. Writing integers of any size as 100 or as 1_00 depends on the user. Ruby allows any number of ‘_’ between its numbers to increase the readability. Look for the below code to get more information.
Code:-
print("200+2_00+10_0 = ", 200+2_00+10_0 ,"\n");
print("Hexa -", 0xaa ,"\n");
print("Octal - ", 0o222 ,"\n");
print("Decimal - ", 0d170, " ", 170,"\n");
print("Binary - ", 0b1010,"\n");
print("Float - ", 1.234E1,"\n");

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Strings
Strings in Ruby behave similarly to the strings in Python. They can be expressed with either "' or ".Strings with "' allows escaped character for interpolation
Code:-
puts( "Five multiply Ten is Fifty : #{5 * 10}")
puts("")
puts("Coding\nNinja\nOne\nStop\nSolution\nfor\nCoding");
puts("")
puts('Coding\nNinjas')

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Symbols
A symbol in ruby represents a name for the ruby interpreter. Symbols are placed inside the ruby interpreter and never collected by garbage. So creating a large number of symbols in ruby would affect the size of the interpreter if not never freed.
Code:-
puts(:":guardian_id#{10+2_5}")

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Ranges
Range in ruby is similar to range() in Python. It helps us print all the value between them, including the boundaries. The syntax for using range goes range1..range2.Both the value in the boundaries are included.
Code:-
for i in 1..5 do
puts(i)
end

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Arrays
An array in ruby is a collection of objects indexed by a non-negative number, created by placing objects between the [ and ].
A Collection of objects indexed by non-negative numbers array object can be created by writing Array. New, by placing comma-separated objects inside the square brackets, or if Array contains only string objects, then a space-delimited string is preceded by %w.
Code:-
# Creating an Array with some string objects
sample = ['Coding', 'Ninja', 'Is', 'The', 'Best']
puts(sample[0])
puts(sample[2])
# We can also use Negative indices. They are counted from the end
print("Negative Index: ", sample[-3], "\n\n")
# [start, count]
puts("[Start Object , Count]: ", sample[0, 3], "\n")
# Using ranges as range size exceeded it prints till full length
puts("Using Range to Print : ", sample[0..7])

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Hashes
A Hash in ruby is created using a key and a value pair. Both key and value could be any objects. It is similar to the dictionary we have in Python. Hash could be created using symbol keys as they are not changeable once they are created and can as perfect keys.
{key : value}

You can also try this code with Online Ruby Compiler
Run Code
Code:-
# Creating a hash sample and initializing it with key and value objects
sample = {"Coding" => 100, "Ninja" => 200, "Is" => 300 , "Best" => 400}
# Printing all keys of the hash
print(sample.keys, "\n")
# Printing Key and Value Pair
for i in sample.keys do
print(i, " => ", sample[i], "\n")
end

You can also try this code with Online Ruby Compiler
Run Code
Output:-

Regular Expressions
A regular expression in ruby is created using “/” for example :
/This is a Regular Expression/

You can also try this code with Online Ruby Compiler
Run Code
The regular expression in Ruby is followed by flags that adjust the matching behaviour of the regular expression. If we want to make regular expression case insensitive, we make the “i” flag, for example:
/This is a Regular Expression/

You can also try this code with Online Ruby Compiler
Run Code
We could also use interpolation inside regular expressions along with escaped characters.
Frequently Asked Questions
What is Ruby?
Ruby is an open-source dynamic language with natural and easy-to-read/write syntax. Ruby is a careful balance language and a perfect blend of five different languages.
Ruby is said to be a combination of which five languages?
Ruby, an open-source dynamic language, is a perfect blend of five different languages (Perl, Smalltalk, Eiffel, Ada, and Lisp).
What are literals in ruby?
Literals in ruby are any constant value which can assign to a variable. We are using literals in ruby every time we type an object.
Is Ruby Case Sensitive?
Ruby is a case-sensitive language, which means lowercase identifiers in ruby are different from uppercase identifiers. E.g. Like_This is entirely different from LIKE_THIS. Similarly, Start is different from START.
What are symbols in ruby?
A symbol in ruby represents a name for the ruby interpreter. Symbols are placed inside the ruby interpreter and never collected by garbage. So creating a large number of symbols in ruby would affect the size of the interpreter if not never freed.
Conclusion
In this article, we have studied literals in ruby in detail and briefly explored multiple types of literals in ruby like boolean and Nil, strings, range, regular expression, hashes, Arrays etc.
Also, visit our Guided Path in Coding Ninjas Studio to learn about Ruby. Upskill yourself in Ruby on Rails, Backend Web Technologies, Hadoop, SQL, MongoDB, Data Structures and Algorithms, JavaScript, System Design and much more!.
To learn more, refer to Operational Databases, Non- relational databases, MongoDB, Top-100-SQL-problems, interview-experience, Introduction to ruby on rails, Directory Structure in Ruby, Ruby on Rails, Ruby vs Python. You can also refer to the Official Ruby, Ruby, Official Documentation, Ruby FAQ, Ruby Koans, Ruby Doc, Why Ruby?
We expect that this article must have helped you enhance your knowledge on the topic of Ruby. Please upvote our blogs if you find them engaging and helpful!
We wish you all the best for your future adventures and Happy Coding.
