Ruby Containers
In Ruby, we can easily put method definition inside a container class, then create new objects by sending the new message to that class like most scripting languages. Ruby has a built-in module called Enumerable that’s included by Strings, Array, Hash, Range, and other classes that represent a collection of values. There are mainly four kinds of containers that represent a collection of data in Ruby:
- Strings: A string is a sequence or set of one or more characters.
- Arrays: Arrays are the collection of ordered, integer-indexed objects.
- Hashes: Hashes are collections of unique <key, value> pairs.
- It is often known as associative arrays, maps, or dictionaries.
- It is unordered.
- Ranges: Ranges depict a set of values between starting and endpoints. Values can be range, character, string, or objects.
Ruby Strings:
Ruby strings are Mutable, and created using single quote(‘ ‘) or double quote(” “) without mentioning the data types.
Example 1:
Ruby
# Ruby code implementation # for creation of Ruby Strings # using single quotes puts 'Ruby String using single quotes in GFG!' # using double quotes puts "Ruby String using double quotes in GFG!" # storing string into variables str = "Ruby String using variable in GFG!" # displaying string puts str |
Output:
Ruby String using single quotes in GFG! Ruby String using double quotes in GFG! Ruby String using a variable in GFG!
Double quotes interpolate the variables whereas single quotes can’t interpolate.
Example 2:
Ruby
# Ruby code implementation to # show single and double quotes str1 = 'Hello Geeks!' str2 = "Hello GFG" # using single quotes puts '#{str1}' puts '#{str2}' puts "#{str1}" puts "#{str2}" |
Output:
#{str1} #{str2} Hello Geeks! Hello GFG
Accessed by mentioning the index inside the square bracket[].
Example 3:
Ruby
# Ruby code implementation # for accessing of Ruby Strings str = "GeeksforGeeks" # accessing the specified substring puts str[ "Geeks" ] # print a single character from a # string using positive index puts str[ 2 ] # print a single character from a # string using negative index puts str[- 2 ] # print string in a range using comma(,) puts str[ 4 , 10 ] # print string in a range using(..) operator puts str[ 4 .. 8 ] |
Output:
Geeks e k sforGeeks sforG
To know more about please refer Ruby Strings article.
Ruby Arrays:
A Ruby array is stored at contiguous memory locations. It is ordered by integer-indexed positions. The 1-D array can be created using a new class method(Array.new) or by using a literal constructor[]
Using new class method
Example 4:
Ruby
# Ruby code implementation for creation of Ruby Arrays # using new method arr = Array . new ( 4 , 'GFG' ) puts arr.size # displaying array elements puts "#{arr}" |
Output:
4 ["GFG", "GFG", "GFG", "GFG"]
Example 5:
Ruby
# Ruby code implementation for creation of Ruby Strings # Using literal[] method arr = Array [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ] # displaying array elements puts "#{arr}" # displaying array size puts "Size of arr is: #{arr.size}" # displaying array length puts "Length of arr is: #{arr.length}" |
Output:
["a", "b", "c", "d", "e", "f"] Size of arr is: 6 Length of arr is: 6
We can retrieve single or multiple elements using both positive and negative indexes:
Example 6:
Ruby
# Ruby code implementation for accessing of Ruby Arrays str = [ "GFG" , "Geeks" , "Ruby" , "Containers" ] # Accessing single array elements puts "Value at index 1: #{str[1]}" # using positive index puts "Value at index -1: #{str[-1]}" # using negative index # Accessing multiple array elements # using positive index range puts "Positive index range [1,2]: #{str[1,2]}" # using negative index range puts "Negative index range [-1,2]: #{str[-1,2]}" |
Output:
Value at index 1: Geeks Value at index -1: Containers Positive index range [1,2]: ["Geeks", "Ruby"] Negative index range [-1,2]: ["Containers"]
Ruby Hashes:
Ruby Hashes is a collection of unique keys and their values, and Hash can be created using literal[], or Hash.new() or try_convert().
Example 7:
Ruby
# Ruby code implementation for creation of Ruby Hashes # Using literal[] puts "Creation of Hashes using literal[]" p Hash [ "x" , 30 , "y" , 19 ] p Hash [ "x" => 30 , "y" => 19 ] # Using of new method puts "\nCreation of Hashes using new" a = Hash . new ( "geeksforgeeks" ) p a[ "x" ] = 40 p a[ "x" ] p a[ "y" ] puts "\nCreation of Hashes using try_convert" # Using of try_convert method p Hash .try_convert({ 3 => 8 }) p Hash .try_convert( "3=>8" ) |
Output:
Creation of Hashes using literal[] {"x"=>30, "y"=>19} {"x"=>30, "y"=>19} Creation of Hashes using new 40 40 "geeksforgeeks" Creation of Hashes using try_convert {3=>8} nil
We can retrieve elements(values) using index(key) which can be anything (integer, character etc.)
Example 8:
Ruby
# Ruby code implementation for accessing of Ruby Hashes a = { "x" => 45 , "y" => 67 } p a[ "x" ] |
Output:
45
The default value of Hashes is nil. To know more about Ruby Hashes click here.
Ruby Ranges:
It is declared using the ”..” and ”…” range operators.
- The “..” operator includes all the variables within the range as well as the starting and end value.
- The “..” operator includes all the variables within the range as well as the starting value but not the end value.
Example 9:
Ruby
#Ruby code to show ranges in Ruby # This will separate the values by comma "," $, = ", " #This include 5 & 10 r1 = ( 5 .. 10 ).to_a #This include 5 but not 10 r2 = ( 5 ... 10 ).to_a #This include "asa" & "asd" r3 = ( 'asa' .. 'asd' ).to_a #This include "asa" but not "asd" r4 = ( 'asa' ... 'asd' ).to_a puts "#{r1}" puts "#{r2}" puts "#{r3}" puts "#{r4}" |
Output:
[5, 6, 7, 8, 9, 10] [5, 6, 7, 8, 9] ["asa", "asb", "asc", "asd"] ["asa", "asb", "asc"]
We can use these ranges as Sequences, Conditions, and Intervals. To know more about Ruby Ranges click here.
Blocks
A block is a sequence of ruby code surrounded by do/end or curly brackets. Methods can take an implicit block argument and call the code in that block with the yield keyword.
Example 10:
Ruby
# Ruby code implementation for creation of Ruby Blocks def two_times yield yield end two_times {puts "GFG!" }; |
Output:
GFG! GFG!
Blocks as Closures:
Blocks can take an argument:
>> def times yield('fir') yield('sec') end => nil >> times {|n| puts "#{n}: yoo"} GFG! Rocks GFG! is the best => nil
Example 11:
Ruby
# Ruby code implementation for creation of Ruby Blocks as Closures def times yield ( "Rocks" ) yield ( "is the best" ) end times {|ys| puts "GFG! #{ys}" } |
Output:
GFG! Rocks GFG! is the best
Yield returns the result of executing the block:
Example 12:
Ruby
# Ruby code implementation for # creation of Ruby Blocks as Closures def gfg [ yield ( "GEEKS" ), yield ( "FOR" ), yield ( "GEEKS" )] end gfg {|geek| puts "#{geek.upcase.reverse}" } |
Output:
SKEEG ROF SKEEG
A closure block can be defined in one scope and can be called in a different scope. To know more about closures in Ruby click here.
More Block Uses:
Blocks are used in many other ways:
Example 13:
Ruby
# Ruby code implementation for # Ruby Blocks using each method [ "Geeks" , "GFG" , 55 ]. each do |n| puts n end |
Output:
Geeks GFG 55
The default:
Ruby
# Ruby code implementation for # Ruby Blocks using times method x = "NULL" 4 .times do |x| puts "Value Inside the block: #{x}" end puts "Value Outside the block: #{x}" |
Output:
Value Inside the block: 0 Value Inside the block: 1 Value Inside the block: 2 Value Inside the block: 3 Value Outside the block: NULL
To know more about Ruby Blocks click here.
Please Login to comment...