Ruby Literals - GeeksforGeeks

23 Feb, 2022
Any constant value which can be assigned to the variable is called as literal/constant. we use literal every time when typing an object in the ruby code. Ruby Literals are same as other programming languages, just a few adjustments, and differences here.These are following literals in Ruby.
Booleans and nilNumbers or IntegersStringsSymbolsRangesArraysHashesRegular Expressions
Booleans and nil
Numbers or Integers
Strings
Symbols
Ranges
Arrays
Hashes
Regular Expressions
Booleans and nil :These are the boolean constants. Here false and nil has the same behavior although nil represents unknown or empty. It behaves as same as false does in conditional statements, but only true or false constants are returned. true behave the same represents a positive variable.true, false, nilExample:# Demo for Boolean literalsputs(3+7==10);# returns trueputs(3+7!=10);# returns falseputs(3+7==nil);# return falseOutput:true
false
false
true, false, nil
Example:
# Demo for Boolean literalsputs(3+7==10);# returns trueputs(3+7!=10);# returns falseputs(3+7==nil);# return false
Output:
true
false
false
Numbers or Integers :Ruby supports all types of Integers. we can write integers of any size as 100 or 1_00 or 10_0. Ruby allows any number of ‘_’ in it’s numbers as it says for readability purposes.Syntax :decimal(0d or 0D)
octal(0o or 0O or 0)
hex-decimal(0x or 0X)
binary(0b or 0B).
float(num- or numE1)
Example :puts("300+1_00+10_0=", 300+1_00+10_0 );puts("hexa-", 0xaa );puts("octal-", 0o222 );puts("decimal-", 0d170, " ", 170);puts("binary-", 0b1010);puts("Float-", 1.234E1);puts("hexa-", aa);# errorOutput :300+1_00+10_0=500
hexa-170
octal-146
decimal-170 170
binary-10
Float-12.34
main.rb:9:in `': undefined local variable or method `aa' for main:Object (NameError)

decimal(0d or 0D)
octal(0o or 0O or 0)
hex-decimal(0x or 0X)
binary(0b or 0B).
float(num- or numE1)

Example :
puts("300+1_00+10_0=", 300+1_00+10_0 );puts("hexa-", 0xaa );puts("octal-", 0o222 );puts("decimal-", 0d170, " ", 170);puts("binary-", 0b1010);puts("Float-", 1.234E1);puts("hexa-", aa);# error
Output :
300+1_00+10_0=500
hexa-170
octal-146
decimal-170 170
binary-10
Float-12.34
main.rb:9:in `': undefined local variable or method `aa' for main:Object (NameError)

String :It is same as python. The string can be expressed with either “” or ”, where “” allows the escaped characters for interpolation.Syntax:#{expression}Example:puts( "Two multiply three is Six : #{2 * 3}")puts("guardians\nof\nthe\ngalaxy");puts('guardians\nof\nthe\ngalaxy')Output :Two multiply three is Six: 6
guardians
of
the
galaxy
guardians\nof\nthe\ngalaxy

#{expression}
Example:
puts( "Two multiply three is Six : #{2 * 3}")puts("guardians\nof\nthe\ngalaxy");puts('guardians\nof\nthe\ngalaxy')
Output :
Two multiply three is Six: 6
guardians
of
the
galaxy
guardians\nof\nthe\ngalaxy

Symbol :In Ruby, a symbol represents a name inside the interpreter. Symbols are placed inside the ruby’s interpreter and never garbage-collected. So, it affects the size of the interpreter, if are created in high amount or never freed.Syntax :ruby_symbolWe can also create symbols keys by interpolation :puts(:":guardian_id#{20+1_5}")Output : :guardian_id35
ruby_symbol
We can also create symbols keys by interpolation :
puts(:":guardian_id#{20+1_5}")
Output :
 :guardian_id35
Ranges :It is similar to the one we have in python range(). Prints all possible values between the given boundaries(including).Syntax :range1..range2Example:for i in 2..5 do    puts(i)endOutput:2
3
4
5

range1..range2
Example:
for i in 2..5 do    puts(i)end
Output:
2
3
4
5

Array :Arrays is a collection of objects, created using ‘[‘ and ‘]’.Example:# Code for Array Demogog = ['Quill', 'Gamora', 'Rocket', 'Groot', 'Drax']puts(gog[0])puts(gog[2])   # Negative indices are counted from the endprint("Negative Index:", gog[-3], "\n\n")  # [start, count]puts("[start, count]:", gog[0, 3], "\n")  # Using ranges.# as range size exceeded it prints till full lengthputs("Using range:", gog[0..7])Output:Quill
Rocket
Negative Index:Rocket

[start, count]:
Quill
Gamora
Rocket

Using range:
Quill
Gamora
Rocket
Groot
Drax

# Code for Array Demogog = ['Quill', 'Gamora', 'Rocket', 'Groot', 'Drax']puts(gog[0])puts(gog[2])   # Negative indices are counted from the endprint("Negative Index:", gog[-3], "\n\n")  # [start, count]puts("[start, count]:", gog[0, 3], "\n")  # Using ranges.# as range size exceeded it prints till full lengthputs("Using range:", gog[0..7])
Output:
Quill
Rocket
Negative Index:Rocket

[start, count]:
Quill
Gamora
Rocket

Using range:
Quill
Gamora
Rocket
Groot
Drax

Hashes :It is similar to the one we have in python. we can create a hash using symbol keys as they are not-changeable once they are created, and can as perfect keys.Syntax :{key:value}Example:# way of creating hashhash1   = Hash.new  # way of creating hashhash2   = {}  # initializing values and keyshash1 = {"Quill" => 100, "Drax" => 200, "Gamora" => 300}  # initializing values and keys with symbol keyshash2 = {Quill:1, Gamora:2}print(hash1.keys, "\n")print(hash2.keys, "\n")for i in hash2.keys do  # : Should be used while checking before# its a part of the symbol key    if i==:Quill       # Printing value and assigned key        print(i, "=>", hash2[i], "\n")    endendOutput:["Quill", "Drax", "Gamora"]
[:Quill, :Gamora]
Quill=>1

{key:value}
Example:
# way of creating hashhash1   = Hash.new  # way of creating hashhash2   = {}  # initializing values and keyshash1 = {"Quill" => 100, "Drax" => 200, "Gamora" => 300}  # initializing values and keys with symbol keyshash2 = {Quill:1, Gamora:2}print(hash1.keys, "\n")print(hash2.keys, "\n")for i in hash2.keys do  # : Should be used while checking before# its a part of the symbol key    if i==:Quill       # Printing value and assigned key        print(i, "=>", hash2[i], "\n")    endend
Output:
["Quill", "Drax", "Gamora"]
[:Quill, :Gamora]
Quill=>1

Regular Expression :It is similar to the one we have in perl {/pattern/}. Regexps in ruby can be created with or without delimiters.Syntax :/pattern/ or %r{pattern}We can create a hash using symbol keys as they not-changeable once created they act as perfect key.Syntax :{key:value}Example:line1 = "guardians of the galaxy";line2 = "Doctor Strange";  # Checks whether ‘of’ is in line1 in // formatif ( line1 =~ /of(.*)/ )   puts line1end  # Checks whether ‘Doc’ is in line1 in %r{} format.if ( line2 =~ %r{Doc(.*)} )   puts line2end  # Checks whether ‘off’ is in line1 .if ( line2 =~ /off(.*)/ )   puts line2else    puts "nothing"endOutput:guardians of the galaxy
Doctor Strange
nothing

/pattern/ or %r{pattern}
We can create a hash using symbol keys as they not-changeable once created they act as perfect key.Syntax :
{key:value}
Example:
line1 = "guardians of the galaxy";line2 = "Doctor Strange";  # Checks whether ‘of’ is in line1 in // formatif ( line1 =~ /of(.*)/ )   puts line1end  # Checks whether ‘Doc’ is in line1 in %r{} format.if ( line2 =~ %r{Doc(.*)} )   puts line2end  # Checks whether ‘off’ is in line1 .if ( line2 =~ /off(.*)/ )   puts line2else    puts "nothing"end
Output:
guardians of the galaxy
Doctor Strange
nothing

ricxpl
Picked
Ruby Collections
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array reverse() function
Instance Variables in Ruby
Ruby | Array transpose() function
Method Overloading In Ruby
Operator Overloading in Ruby
Ruby | Array unshift() function
Ruby Static Members
Ruby | Array class insert() function
Ruby on Rails Introduction
Ruby | clear() function