Ruby Literals
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 nil
- Numbers or Integers
- Strings
- Symbols
- Ranges
- Arrays
- Hashes
- Regular Expressions
Type of Ruby Literals
- 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, nil
Example:
# Demo for Boolean literalsputs(3+7==10);# returns trueputs(3+7!=10);# returns falseputs(3+7==nil);# return falsechevron_rightfilter_noneOutput:
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 oB). 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);# errorchevron_rightfilter_noneOutput :
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')chevron_rightfilter_noneOutput :
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_symbol
We can also create symbols keys by interpolation :
puts(:":guardian_id#{20+1_5}")chevron_rightfilter_noneOutput :
: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..range2
Example:
foriin2..5doputs(i)endchevron_rightfilter_noneOutput:
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])chevron_rightfilter_noneOutput:
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")foriinhash2.keysdo# : Should be used while checking before# its a part of the symbol keyifi==:Quill# Printing value and assigned keyprint(i,"=>", hash2[i],"\n")endendchevron_rightfilter_noneOutput:
["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 line2elseputs"nothing"endchevron_rightfilter_noneOutput:
guardians of the galaxy Doctor Strange nothing
Recommended Posts:
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



