Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Ruby
3.
Lexical Structure in Ruby
4.
Literals in Ruby
4.1.
Booleans and Nil
4.2.
Numbers
4.3.
Strings
4.4.
Symbols
4.5.
Ranges
4.6.
Arrays
4.7.
Hashes
4.8.
Regular Expressions
5.
Frequently Asked Questions
5.1.
What is Ruby?
5.2.
Ruby is said to be a combination of which five languages?
5.3.
What are literals in ruby?
5.4.
Is Ruby Case Sensitive?
5.5.
What are symbols in ruby?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Literals in Ruby

Author Gaurav Joshi
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

Whether you are an engineer in the software industry or associated with it, we all know what a variable is. Variables are the only access to storage or, in laymen's terms, storage that helps us store any value during the program. We all must have wondered what all values these variables could hold. These values are nothing but literal. Literals in ruby are any constant value that we can assign to a variable. 

We will look into literals in ruby in detail in the coming section, but before that, we must briefly understand ruby. So let's discuss What Ruby is? 

Ruby

Ruby

Ruby

Ruby is an open-source dynamic language with natural and easy-to-read/write syntax. Ruby is a language of careful balance and is a perfect blend of five different languages  (Perl, Smalltalk, Eiffel, Ada, and Lisp). Often, its creator  Yukihiro "Matz" Matsumoto considers ruby as a human being in the sense that the way human beings are simple from the outside but complex from the inside. Like human bodies, ruby is simple in appearance but complex on the inside. So I think you get to know in brief about ruby, so let us have a brief idea about lexical structure in Ruby before we go into details to understand literals in ruby.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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


Output:-

terminal 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");


Output:-

terminal 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')


Output:-

terminal 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}")


Output:-

terminal 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


Output:-

terminal 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])


Output:-

terminal 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}

 

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

 

Output:-

terminal output

Regular Expressions

A regular expression in ruby is created using “/” for example :

/This is a Regular Expression/


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/


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 RailsBackend Web TechnologiesHadoopSQL, MongoDB, Data Structures and Algorithms, JavaScript,  System Design and much more!. 

To learn more, refer to Operational DatabasesNon- relational databasesMongoDBTop-100-SQL-problemsinterview-experienceIntroduction to ruby on railsDirectory Structure in RubyRuby on RailsRuby vs Python. You can also refer to the Official RubyRubyOfficial DocumentationRuby FAQRuby KoansRuby DocWhy 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. 

Conclusion

Previous article
Whitespace in ruby
Next article
Identifiers in Ruby
Live masterclass