Ruby Containers
Last Updated :
29 Nov, 2022
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
puts 'Ruby String using single quotes in GFG!'
puts "Ruby String using double quotes in GFG!"
str = "Ruby String using variable in GFG!"
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
str1 = 'Hello Geeks!'
str2 = "Hello GFG"
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
str = "GeeksforGeeks"
puts str[ "Geeks" ]
puts str[ 2 ]
puts str[- 2 ]
puts str[ 4 , 10 ]
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
arr = Array . new ( 4 , 'GFG' )
puts arr.size
puts "#{arr}"
|
Output:
4
["GFG", "GFG", "GFG", "GFG"]
Example 5:
Ruby
arr = Array [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ]
puts "#{arr}"
puts "Size of arr is: #{arr.size}"
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
str = [ "GFG" , "Geeks" , "Ruby" , "Containers" ]
puts "Value at index 1: #{str[1]}" # using positive index
puts "Value at index -1: #{str[-1]}" # using negative index
puts "Positive index range [1,2]: #{str[1,2]}"
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
puts "Creation of Hashes using literal[]"
p Hash [ "x" , 30 , "y" , 19 ]
p Hash [ "x" => 30 , "y" => 19 ]
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"
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
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
$, = ", "
r1 = ( 5 .. 10 ).to_a
r2 = ( 5 ... 10 ).to_a
r3 = ( 'asa' .. 'asd' ).to_a
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
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
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
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
[ "Geeks" , "GFG" , 55 ]. each do |n|
puts n
end
|
Output:
Geeks
GFG
55
The default:
Ruby
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...