In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order. The default value of Hashes is nil. When a user tries to access the keys which do not exist in the hash, then the nil value is returned.
Class Method
1. [] : This method creates a new hash that is populated with the given objects. It is equivalent to creating a hash using literal {Key=>value....}. Keys and values are present in the pair so there is even number of arguments present.
Hash[(key=>value)*]
Example:
Ruby
# Ruby program to illustrate
# use of []
# Using []
p Hash["x", 30, "y", 19]
p Hash["x" => 30, "y" => 19]
Output:
{"x"=>30, "y"=>19}
{"x"=>30, "y"=>19}
2. new : This method returns a empty hash. If a hash is subsequently accessed by the key that does not match to the hash entry, the value returned by this method depends upon the style of new used to create a hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value. The values are stored in the hash (if necessary) depends upon the block.
Hash.new
Hash.new(obj)
Hash.new{|hash, key|block}
Example:
Ruby
# Ruby program to illustrate
# use of new method
# Using new method
a = Hash.new("geeksforgeeks")
p a["x"] = 40
p a["y"] = 49
p a["x"]
p a["y"]
p a["z"]
Output:
40
49
40
49
"geeksforgeeks"
3.try_convert : This method is used to convert obj into hash and returns hash or nil. It return nil when the obj does not convert into hash.
Hash.try_convert(obj)
Example:
Ruby
# Ruby program to illustrate
# use of try_convert method
# Using try_convert method
p Hash.try_convert({3=>8})
p Hash.try_convert("3=>8")
Output:
{3=>8}
nil
Instance Method
Note: In the below-described methods, hsh variable is the instance of the Hash Class.
1. ==: It is known as Equality. It is used to check if two hashes are equal or not. If they are equal means they contain the same number of keys and the value related to these keys are equal, then it will return true otherwise returns false.
hsh1 == hsh2
Example:
Ruby
# Ruby program to illustrate
# use of Equality
a1 = {"x" => 4, "y" => 109}
a2 = {"x" => 67, "f" => 78, "z" => 21}
a3 = {"f" => 78, "x" => 67, "z" => 21}
# Using equality
p a1 == a2
p a2 == a3
Output:
false
true
2. [] : It is known as Element Reference. It retrieves the value that stored in the key. If it does not find any value then it return the default value.
hsh[key]
Example:
Ruby
# Ruby program to illustrate
# use of []
a = {"x" => 45, "y" => 67}
# Using []
p a["x"]
p a["z"]
Output:
45
nil
3. []= : It is known as Element Assignment. It associates the value given by value with the key given by key.
hsh[key]=value
Example:
Ruby
# Ruby program to illustrate
# use of []=
a = {"x" => 45, "y" => 67}
# Using []=
a["x"]= 34
a["z"]= 89
p a
Output:
{"x"=>34, "y"=>67, "z"=>89}
4. clear : This method removes all the keys and their values from the hsh.
hsh.clear
Example:
Ruby
# Ruby program to illustrate
# use of clear method
a = {"x" => 45, "y" => 67}
# Using clear method
p a.clear
Output:
{}
5. default : This method return the default value. The value that returned by hsh[key], if key did not exist in hsh.
hsh.default(nil=key)
Example:
Ruby
# Ruby program to illustrate
# use of default method
a = Hash.new("geeksforgeeks")
# Using default method
p a.default
p a.default(2)
Output:
"geeksforgeeks"
"geeksforgeeks"
6. default= : This method sets the default value (the value which is returned for a key and not exists in a hash).
hsh.default=obj
7. default_proc : In this method if Hash.new was called with the block. Then it will return block otherwise return nil.
hsh.default_proc
Example:
Ruby
# Ruby program to illustrate
# use of default_proc method
a = Hash.new {|a, v| a[v] = v*v*v}
# Using default_proc method
b = a.default_proc
c = []
p b.call(c, 2)
p c
Output:
8
[nil, nil, 8]
8. delete :This method is used to delete the entry from hash whose key is key by returning the corresponding value. If the key is not found, then this method returns nil. If the optional block is given and the key is not found, then it will pass the block and return the result of the block.
hsh.delete(key)
hsh.delete(key){|key|block}
Example:
Ruby
# Ruby program to illustrate
# use of delete method
a = {"x" => 34, "y" => 60}
# Using delete method
p a.delete("x")
p a.delete("z")
Output:
34
nil
9. delete_if : This method deletes the keys and their values from the hsh when the block is true.
hsh.delete_if{|key, value|block}
Example:
Ruby
# Ruby program to illustrate
# use of delete_if method
a = {"x" => 34, "y" => 60}
# Using delete_if method
p a.delete_if {|key, value| key >= "y"}
Output:
{"x"=>34}
10. each : This method calls block once for each key that present in hsh and pass key and value as a parameter.
hsh.each{|key, value|block}
Example:
Ruby
# Ruby program to illustrate
# use of each method
a = {"x" => 34, "y" => 60}
# Using each method
a.each {|key, value| puts "the value of #{key} is #{value}" }
Output:
the value of x is 34
the value of y is 60
11. each_key : This method calls block once for each key that present in hsh and pass the key as a parameter.
hsh.each_key{|key|block}
Example:
Ruby
# Ruby program to illustrate
# use of each_key method
a = { "x" => 34, "y" => 60 }
# Using the each_key method
a.each_key {|key| puts key }
Output:
x
y
12. each_pair : This method is similar to Hash#each method.
hsh.each_pair{|key, value|block}
13. each_value : This method calls block once for each key that present in hsh and pass value as a parameter.
hsh.each_key{|value|block}
Example:
Ruby
# Ruby program to illustrate
# use of each_value method
# Using each_value method
a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }
a.each_value{|value| puts value }
Output:
23
25
3432
3453
676
14.empty?: This method return true if hsh does not contain any key and value pair. Otherwise, return false.
hsh.empty?
15. fetch : This method return a value from the hsh using the given key. If the key is not found then it gives result depends on following conditions:
- If no argument, then it will raise an exception.
- If the default is given the it will return the default .
- If an option block is present, then it will run the block and return the result of the block.
fetch method does not contain any default value. When the hash is created then it will only gaze for keys that present in the hash.
hsh.fetch(key[, default])
hsh.fetch(key){|key|block}
16. has_key? : This method return true if the given key is present in the hsh, otherwise, return false.
hsh.has_key?
Example:
Ruby
# Ruby program to illustrate
# use of has_key? method
a = {"g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676}
# Using has_key? method
p a.has_key?("x")
p a.has_key?("p")
Output:
true
false
17. has_value? : This method return true if the given value is present for a key in the hsh, otherwise, return false.
hsh.has_value?
Example:
Ruby
# Ruby program to illustrate
# use of has_value? method
a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }
# Using has_value? method
p a.has_value?(23)
p a.has_value?(234)
Output:
true
false
18. include? : This method is similar to Hash#has_key? method.
hsh.include?
19. index : This method return the key that contain the given value. If multiple key contains the given value, then it will return only a single key from all the keys and if not found then return nil. This is a Deprecated method. So we have to use Hash#key instead.
hsh.index(value)
20. invert : This method returns a new hash created by hsh's values as keys and the keys as values. If duplicate values are found, then it will contain only a single value is key from all the values.
hsh.invert
Example:
Ruby
# Ruby program to illustrate
# use of invert method
a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }
# Using invert method
p a.invert
Output:
{23=>"g", 25=>"h", 3432=>"x", 3453=>"y", 676=>"z"}
21. key? : This method is similar to Hash#has_key?.
hsh.key?(key)
22. keys : This method returns an array of keys that present in the hash.
hsh.keys
23. length : This method returns the number of key and value pair from the hsh.
hsh.length
Example:
Ruby
# Ruby program to illustrate
# use of length method
a = {"g" => 23, "h" => 25}
# Using the length method
p a.length
Output:
2
24. member? : This method is similar to Hash#has_key?.
hsh.member?(key)
25. merge : This method return new hash that contains the other_hsh content. If a block is specified, then each duplicate keys and their values is called from both the hashes and the value stored in the new hash.
hsh.merge(other_hsh)
hsh.merge(other_hsh){|key, old_value, new_value|block}
Example:
Ruby
# Ruby program to illustrate
# use of merge method
a1 = { "g" => 23, "h" => 25 }
a2 = { "h" => 2343, "i" => 4340 }
# Using merge method
p a1.merge(a2)
Output:
{"g"=>23, "h"=>2343, "i"=>4340}
26. merge! : This method merges the content of one hsh into another hsh and overwrite entries with duplicate keys with those from other_hsh.
hsh.merge!(other_hsh)
hsh.merge!(other_hsh){|key, old_value, new_value|block}
Example:
Ruby
# Ruby program to illustrate
# use of merge! method
a1 = {"g" => 23, "h" => 25}
a2 = {"h" => 2343, "i" => 4340}
# Using merge! method
p a1.merge!(a2)
a1 = {"g" => 23, "h" => 25 }
# Using merge! method
p a1.merge!(a2) {|x, y, z| y}
p a1
Output:
{"g"=>23, "h"=>2343, "i"=>4340}
{"g"=>23, "h"=>25, "i"=>4340}
{"g"=>23, "h"=>25, "i"=>4340}
27. rehash : This method recreate the hash based on the current hash value from each key. If the value of the keys hash changed, then it will re-index the hsh.
hsh.rehash
Example:
Ruby
# Ruby program to illustrate
# use of rehash method
x = [ "x", "g" ]
y = [ "y", "f" ]
a = { x => 45345, y => 6756 }
p a[x]
p x[0] = "h"
p a[x]
# Using rehash method
p a.rehash
p a[x]
Output:
45345
"h"
nil
{["h", "g"]=>45345, ["y", "f"]=>6756}
45345
28. reject : This method is similar to Hash#delete_if, but it return the copy of hsh
hsh.reject{|key, value|block}
29. reject! : This method is similar to Hash#delete_if, but return nil if no changes take place.
hsh.reject!{|key, value|block}
30. replace : This method replace the content of hsh from other_hsh.
hsh.replace(other_hsh)
Example:
Ruby
# Ruby program to illustrate
# use of replace method
a = { "x" => 34, "y" => 60, "z"=>33 }
# Using replace method
p a.replace({ "y" => 88, "x" => 987 })
Output:
{"y"=>88, "x"=>987}
31. select : This method returns a new array that consists of a key and value pair only for which the given condition in the block is true.
hsh.select{|key, value| block}
Example:
Ruby
# Ruby program to illustrate
# use of select method
a = { "x" => 34, "y" => 60, "z"=>33 }
# Using select method
p a.select {|g, f| g > "x"}
Output:
{"y"=>60, "z"=>33}
32. shift : This method remove the key and value pair from the hsh and return them as a two-item array. If the hshdoes not contain any pair then return nil.
hsh.shift
Example:
Ruby
# Ruby program to illustrate
# use of shift method
a = { "x" => 34, "y" => 60, "z"=>33 }
# Using the shift method
p a.shift
p a
Output:
["x", 34]
{"y"=>60, "z"=>33}
33. size : This method is similar to Hash#length.
hsh.size
34. sort : This method converts the hsh to the nested array of arrays that contains keys and their values and sort them by using Array#sort.
hsh.sort
hsh.sort{|a, b|block}
Example:
Ruby
# Ruby program to illustrate
# use of sort method
a = { "x" => 34, "y" => 60, "z"=>33 }
# Using sort method
p a.sort
p a.sort {|x, y| x[1]<=>y[1]}
Output:
[["x", 34], ["y", 60], ["z", 33]]
[["z", 33], ["x", 34], ["y", 60]]
35. store : This method is similar to Hash#[]=.
hsh.store(key, value)
36. to_a : This method convert the hsh to the nested array of arrays that contains keys and their values.
hsh.to_a
Example:
Ruby
# Ruby program to illustrate
# use of to_a method
a = { "x" => 34, "y" => 60, "z"=>33 }
# Using to_a method
p a.to_a
Output:
[["x", 34], ["y", 60], ["z", 33]]
37. to_s : This method convert hsh into a string. In other words, it converts the hash array, i.e. key and value pair in a string.
hsh.to_s
38. update : This method is similar to Hash#merge!.
hsh.update(other_hsh)
hsh.update(other_hsh){|key, old_value, new_value|block}
39. value? : This method is similar to Hash#has_value?.
hsh.value?(value)
40. values : This method returns an array which contains the values that present in hsh.
hsh.values
41. values_at : This method returns an array that contains the values of the specified keys and also provide default values for the keys that are not found.
hsh.values_at([keys])
Example:
Ruby
# Ruby program to illustrate
# use of values_at method
a = {"x" => 34, "y" => 60, "z"=>33}
# Using values_at method
p a.values_at("x", "y")
# Using default method
a.default = "geeks"
# Using values_at method
p a.values_at("x", "y", "z", "g")
Output:
[34, 60]
[34, 60, 33, "geeks"]
Reference: https://docs.ruby-lang.org/en/2.0.0/Hash.html
Similar Reads
Ruby Programming Language Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Rubyâs develop
2 min read
Overview
Ruby For BeginnersRuby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. This article will cover its basic syntax and some basic programs. This article is divided into various sections for various topi
3 min read
Ruby Programming Language (Introduction)Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990âs in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby's development was to make
4 min read
Comparison of Java with Other Programming LanguagesJava is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming cons
4 min read
Similarities and Differences between Ruby and C languageSimilarities between Ruby and C There are many similarities between C and Ruby, and some of them are: Like C, in Ruby also⦠A programmer is able to program procedurally if they like to do. But still, behind the scenes, it will be object-oriented.Both the languages have the same operators, for exampl
3 min read
Similarities and Differences between Ruby and C++There are many similarities between C++ and Ruby, some of them are: Just like C++, in Ruby⦠As in C++, public, private, and protected works similarly in Ruby also .Inheritance syntax is still only one character, but itâs < instead of : in Ruby.The way ânamespaceâ is used in C++, in the similar wa
3 min read
Environment Setup in RubyRuby is an interpreted, high-level, general-purpose programming language. Ruby is dynamically typed and uses garbage collection. It supports multiple programming paradigms, object-oriented, including procedural and functional programming. Ruby is based on many other languages like Perl, Lisp, Smallt
3 min read
How to install Ruby on Linux?Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Linux, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything
2 min read
How to install Ruby on Windows?Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everythi
2 min read
Interesting facts about Ruby Programming LanguageRuby is an interpreted, high-level, dynamic, general-purpose, open source programming language which focuses on simplicity and productivity. It was designed and developed in the mid-1990s by Yukihiro Matsumoto (also known as Matz in the Ruby community) in Japan. Here are some interesting facts about
2 min read
Basics
Ruby | KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error. Example: Ruby # Ruby program to
4 min read
Ruby | Data TypesData types in Ruby represents different types of data like text, string, numbers, etc. All data types are based on classes because it is a pure Object-Oriented language. There are different data types in Ruby as follows: NumbersBooleanStringsHashesArraysSymbols Numbers: Generally a number is defined
3 min read
Ruby Basic SyntaxRuby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990âs in Japan. To program in Ruby is easy to learn because of its similar syntax to already widely used languages. Here, we will learn the basic syntax of Ruby language. Le
3 min read
Hello World in RubyRuby is a dynamic, reflective, object-oriented, general-purpose programming language. Hello World the program is the most basic and first program when we start a new programming language. This simply prints Hello World on the screen. Below is the program to write hello world". How to run a Ruby Prog
2 min read
Ruby | Types of VariablesThere are different types of variables in Ruby: Local variables Instance variables Class variables Global variables Each variable in Ruby is declared by using a special character at the start of the variable name which is mentioned in the following table: Symbol Type of Variable [a-z] or _ Local Var
4 min read
Global Variable in RubyGlobal Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($). If we want to have a single variable, which is available across classes, we n
2 min read
Comments in RubyStatements that are not executed by the compiler and interpreter are called Comments. During coding proper use of comments makes maintenance easier and finding bugs easily.In Ruby, there are two types of comments:Â Â Single â line comments.Multi â line comments. Here, we are going to explain both typ
2 min read
Ruby | RangesPrerequisite: Ruby Range Operator Ruby ranges depict a set of values with a beginning and an end. Values of a range can be numbers, characters, strings or objects. It is constructed using start_point..end_point, start_point...endpoint literals, or with ::new. It provides the flexibility to the code
4 min read
Ruby LiteralsAny 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. Boolean
4 min read
Ruby DirectoriesA directory is a location where files can be stored. For Ruby, the Dir class and the FileUtils module manages directories and the File class handles the files. Double dot (..) refers to the parent directory for directories and single dot(.)refers to the directory itself.The Dir Class The Dir class p
5 min read
Ruby | OperatorsAn operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows: Arithmetic
11 min read
Operator Precedence in RubyOperators are used to perform different kinds of operations on operands. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. when two operators of the same precedence appear in expression associativity is use
2 min read
Operator Overloading in RubyRuby permits operator overloading, allowing one to define how an operator shall be used in a particular program. For example a '+' operator can be define in such a way to perform subtraction instead addition and vice versa. The operators that can be overloaded are +, -, /, *, **, %, etc and some ope
5 min read
Ruby | Pre-define Variables & ConstantsRuby Predefine Variables Ruby contains a wide range of predefined variables. Every predefined variable has its own specification. You can use predefine variables to perform a specific task like when dealing with interpreter parameters or regular expressions. The list of predefined variables in Ruby
5 min read
Ruby | unless Statement and unless ModifierRuby provides a special statement which is referred as unless statement. This statement is executed when the given condition is false. It is opposite of if statement. In if statement, the block executes once the given condition is true, however in unless statement, the block of code executes once th
2 min read
Control Statements
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. Th
3 min read
Ruby | Loops (for, while, do..while, until)Looping is a fundamental concept in programming that allows for the repeated execution of a block of code based on a condition. Ruby, being a flexible and dynamic language, provides various types of loops that can be used to handle condition-based iterations. These loops simplify tasks that require
5 min read
Ruby | Case StatementThe case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression. There are 3 important keywords which are used in the case statement: case: It is similar to
3 min read
Ruby | Control Flow AlterationPrerequisite : Decision Making , Loops Ruby programming language provides some statements in addition to loops, conditionals, and iterators, which are used to change the flow of control in a program. In other words, these statements are a piece of code that executes one after another until the condi
7 min read
Ruby Break and Next StatementIn Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. Syntax : Break Example : Ruby # Ruby program to use break statement #!/usr/bin/ruby -w i
2 min read
Ruby redo and retry StatementIn Ruby, Redo statement is used to repeat the current iteration of the loop. redo always used inside the loop. The redo statement restarts the loop without evaluating the condition again. Ruby # Ruby program of using redo statement #!/usr/bin/ruby restart = false # Using for loop for x in 2..20 if x
2 min read
BEGIN and END Blocks In RubyEvery Ruby source file can run as the BEGIN blocks when the file is being loaded and runs the END blocks after the program has finished executing. The BEGIN and END statements are different from each other. A program may contain multiple BEGIN and END blocks. If there is more than one BEGIN statemen
2 min read
File Handling in RubyIt is a way of processing a file such as creating a new file, reading content in a file, writing content to a file, appending content to a file, renaming the file and deleting the file. Common modes for File Handling "r" : Read-only mode for a file. "r+" : Read-Write mode for a file. "w" : Write-onl
4 min read
Methods
OOP Concepts
Object-Oriented Programming in Ruby | Set 1When we say object-oriented programming, we mean that our code is centered on objects. Objects are real-life instances that are classified into various types. Letâs take an example to understand this better. If we consider a rose as an object, then the class of the rose will be flower. A class is li
9 min read
Object Oriented Programming in Ruby | Set-2Prerequisite: Object Oriented Programming in Ruby | Set-1 Inheritance Inheritance is one of the solid fundamental characteristics of object-oriented programming. sometimes we might need certain features of a class to be replicated into another class. Instead of creating that attribute again, we can
8 min read
Ruby | Class & ObjectRuby is an ideal object-oriented programming language. The features of an object-oriented programming language include data encapsulation, polymorphism, inheritance, data abstraction, operator overloading etc. In object-oriented programming classes and objects plays an important role. A class is a b
4 min read
Private Classes in RubyThe concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby. Private Class When a constant is declared private in Ruby, it means this constant can never b
3 min read
Freezing Objects | RubyAny object can be frozen by invoking Object#freeze. A frozen object can not be modified: we can't change its instance variables, we can't associate singleton methods with it, and, if it is a class or module, we can't add, delete, or modify its methods. To test if an object is frozen we can use Objec
2 min read
Ruby | InheritanceRuby is the ideal object-oriented language. In an object-oriented programming language, inheritance is one of the most important features. Inheritance allows the programmer to inherit the characteristics of one class into another class. Ruby supports only single class inheritance, it does not suppor
4 min read
Polymorphism in RubyIn Ruby, one does not have anything like the variable types as there is in other programming languages. Every variable is an "object" which can be individually modified. One can easily add methods and functions on every object. So here, the Object Oriented Programming plays a major role. There are m
3 min read
Ruby | ConstructorsA constructor is a special method of the class that gets automatically invoked whenever an instance of the class is created. Like methods, a constructor may also contain a group of instructions or a method that will execute at the time of object creation. Important points to remember about Construct
2 min read
Ruby | Access ControlAccess control is a very important part of the object-oriented programming language which is used to restrict the visibility of methods and member fields to protect data from the accidental modification. In terms of access control, Ruby is different from all other Object Oriented Programming languag
8 min read
Ruby | EncapsulationEncapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encap
2 min read
Ruby MixinsBefore studying about Ruby Mixins, we should have the knowledge about Object Oriented Concepts. If we don't, go through Object Oriented Concepts in Ruby . When a class can inherit features from more than one parent class, the class is supposed to have multiple inheritance. But Ruby does not support
3 min read
Instance Variables in RubyThere are four different types of variables in Ruby- Local variables, Instance variables, Class variables and Global variables. An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though the
3 min read
Data Abstraction in RubyThe idea of representing significant details and hiding details of functionality is called data abstraction. The interface and the implementation are isolated by this programming technique. Data abstraction is one of the object oriented programming features as well. Abstraction is trying to minimize
3 min read
Ruby Static MembersIn Programming, static keywords are primarily used for memory management. The static keyword is used to share the same method or variable of a class across the objects of that class. There are various members of a class in Ruby. Once an object is created in Ruby, the methods and variables for that o
3 min read
Exceptions
Ruby | ExceptionsA good program(or programmer) predict error and arrange to handle them in an effective manner. This is not as easy as it sounds. Exceptions are the errors that occur at runtime. It halts the execution of a program. They are caused by an extensive variety of exceptional circumstances, such as running
4 min read
Ruby | Exception handlingIn Ruby, exception handling is a process which describes a way to handle the error raised in a program. Here, error means an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions. So these types of
6 min read
Catch and Throw Exception In RubyAn exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that's not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is si
3 min read
Raising Exceptions in RubyAn exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the programâs instructions. As we know, the code enclosed between begin and end block is totally secured for handling Exceptions and the rescue block tells
4 min read
Ruby | Exception Handling in Threads | Set - 1Threads can also contain exceptions. In Ruby threads, the only exception arose in the main thread is handled but if an exception arises in the thread(other than main thread) cause the termination of the thread. The arising of an exception in a thread other than the main thread depends upon abort_on_
2 min read
Ruby | Exception Class and its MethodsAn exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at runtime, that disrupts the normal flow of the programâs instructions. In Ruby, descendants of an Exception class are used to interface between raise methods and rescue statements in the begin or
3 min read
Ruby Regex
Ruby Classes
Ruby Module
Ruby | ModuleA Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword. Important Points about Modules: You cannot inherit modules or you can't create a subclass of a module. Objects cannot be created from a module. Mod
4 min read
Ruby | Comparable ModuleIn Ruby, the mixin of Comparable is used by the class whose objects may be ordered. The class must be defined using an operator which compare the receiver against another object. It will return -1, 0, and 1 depending upon the receiver. If the receiver is less than another object, then it returns -1,
3 min read
Ruby | Math ModuleIn Ruby, Modules are defined as a collection of methods, classes, and constants together. Math module consists of the module methods for basic trigonometric and transcendental functions. Module ConstantsNameDescriptionEDefine the value of base of natural logarithm e.PIDefine the value of Ï. Example:
4 min read
Include v/s Extend in RubyInclude is used to importing module code. Ruby will throw an error when we try to access the methods of import module with the class directly because it gets imported as a subclass for the superclass. So, the only way is to access it through the instance of the class. Extend is also used to importin
2 min read