<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nishant Mishra on Medium]]></title>
        <description><![CDATA[Stories by Nishant Mishra on Medium]]></description>
        <link>https://medium.com/@nishantdev02?source=rss-11aa231e6883------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wkSdft1G05UsZxN1LB6K8Q.jpeg</url>
            <title>Stories by Nishant Mishra on Medium</title>
            <link>https://medium.com/@nishantdev02?source=rss-11aa231e6883------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:07:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nishantdev02/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Introduction to Object-Oriented Programming with Ruby]]></title>
            <link>https://medium.com/free-code-camp/an-introduction-to-object-oriented-programming-with-ruby-73531e2b8ddc?source=rss-11aa231e6883------2</link>
            <guid isPermaLink="false">https://medium.com/p/73531e2b8ddc</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Nishant Mishra]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 03:29:08 GMT</pubDate>
            <atom:updated>2018-03-15T03:29:08.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCQfbNxV9hutPmznUcRA4Q.jpeg" /></figure><p>As a computer science student, I spend a lot of time learning and playing with new languages. Every new language has something unique to offer. Having said that, most beginners start off their programming journey with either procedural languages like C or with object-oriented languages like JavaScript and C++.</p><p>Therefore, it makes sense to go through the basics of object-oriented programming so you can understand the concepts and apply them to the languages you learn easily. We’ll be using the Ruby programming language as an example.</p><p>You may be asking, why Ruby? Because it is “designed to make programmers happy” and also because almost everything in Ruby is an object.</p><h3>Getting a sense of the Object-Oriented Paradigm (OOP)</h3><p>In OOP, we identify the “things” that our program handles. As humans, we think about things as objects with attributes and behaviors, and we interact with things based on these attributes and behaviors. A thing can be a car, a book, and so on. Such things become classes (the blueprints of objects), and we create objects out of these classes.</p><p>Each instance (object) contains instance variables which are the state of the object (attributes). Object behaviors are represented by methods.</p><p>Let’s take the example of a car. A car is a thing which would make it a <strong>class</strong>. A specific type of car, say BMW is an <strong>object</strong> of the class Car<em>. </em>The <strong>attributes/properties</strong> of a BMW such as the color and model number can be stored in instance variables. And if you want to perform an operation of the object, such as driving, then “drive” describes a behavior which is defined as a <strong>method</strong>.</p><h3>A Quick Syntax Lesson</h3><ul><li>To end a line in a Ruby program, a semicolon(;) is optional (but is generally not used)</li><li>2-space indentation for each nested level is encouraged (not required, like it is in Python)</li><li>No curly braces {} are used, and the <strong>end</strong> keyword is used to mark the end of a flow control block</li><li>To comment, we use the # symbol</li></ul><p>The way objects are created in Ruby is by calling a <strong>new</strong> method on a class, as in the example below:</p><pre>class Car<br>  def initialize(name, color)<br>    @name = name<br>    @color = color<br>  end</pre><pre>  def get_info<br>    &quot;Name: #{@name}, and Color: #{@color}&quot;<br>  end<br>end</pre><pre>my_car = Car.new(&quot;Fiat&quot;, &quot;Red&quot;)<br>puts my_car.get_info</pre><p>To understand what’s going on in the code above:</p><ul><li>We have a class named Car with two methods, initialize and get_info.</li><li>Instance variables in Ruby begin with @ (For example @name). The interesting part is that the variables are not initially declared. They spring into existence when first used, and after that they are available to all instance methods of the class.</li><li>Calling the new method causes the initialize method to invoke. initialize is a special method which is used as a constructor.</li></ul><h4>Accessing Data</h4><p>Instance variables are private and can’t be accessed from outside the class. In order to access them, we need to create methods. Instance methods have public access by default. We can limit the access to these instance methods as we will see later in this article.</p><p>In order to get and modify the data, we need “getter” and “setter” methods, respectively. Let’s look at these methods taking the same example of a car.</p><pre>class Car<br>  def initialize(name, color) # <em>&quot;Constructor&quot;</em><br>    @name = name<br>    @color = color<br>  end</pre><pre>  def color<br>    @color<br>  end</pre><pre>  def color= (new_color)<br>    @color = new_color<br>  end<br>end</pre><pre>my_car = Car.new(&quot;Fiat&quot;, &quot;Red&quot;)<br>puts my_car.color # <em>Red</em></pre><pre>my_car.color = &quot;White&quot;<br>puts my_car.color # <em>White</em></pre><p>In Ruby, the “getter” and the “setter” are defined with the same name as the instance variable that we are dealing with.</p><p>In the example above, when we say my_car.color, it actually calls the color method which in turn returns the name of the color.</p><p><em>Note: Pay attention to how Ruby allows a space between the </em>color<em> and </em><strong><em>equals to sign</em></strong><em> while using the setter, even though the method name is </em>color=</p><p>Writing these getter/setter methods allow us to have more control. But most of the time, getting the existing value and setting a new value is simple. So, there should be an easier way instead of actually defining getter/setter methods.</p><h4>The easier way</h4><p>By using the attr_* form instead, we can get the existing value and set a new value.</p><ul><li>attr_accessor: for getter and setter both</li><li>attr_reader: for getter only</li><li>attr_writer: for setter only</li></ul><p>Let’s look at this form taking the same example of a car.</p><pre>class Car<br>  attr_accessor :name, :color<br>end</pre><pre>car1 = Car.new<br>puts car1.name # <em>=&gt; nil</em></pre><pre>car1.name = &quot;Suzuki&quot;<br>car1.color = &quot;Gray&quot;<br>puts car1.color # =&gt; <em>Gray</em></pre><pre>car1.name = &quot;Fiat&quot;<br>puts car1.name # =&gt; <em>Fiat</em></pre><p>This way we can skip the getter/setter definitions altogether.</p><h4>Talking about best practices</h4><p>In the example above, we didn’t initialize the values for the @name and @color instance variables, which is not a good practice. Also, as the instance variables are set to nil, the object car1 doesn’t make any sense. It’s always a good practice to set instance variables using a constructor as in the example below.</p><pre>class Car<br>  attr_accessor :name, :color<br>  <br>  def initialize(name, color)<br>    @name = name<br>    @color = color<br>  end<br>end</pre><pre>car1 = Car.new(&quot;Suzuki&quot;, &quot;Gray&quot;)<br><br>puts car1.color # =&gt; <em>Gray</em></pre><pre>car1.name = &quot;Fiat&quot;<br>puts car1.name # =&gt; <em>Fiat</em></pre><h3>Class Methods and Class Variables</h3><p>So class methods are invoked on a class, not on an instance of a class. These are similar to <strong>static </strong>methods in Java.</p><p><em>Note: </em><em>self outside of the method definition refers to the class object. Class variables begin with </em><em>@@</em></p><p>Now, there are actually three ways to define class methods in Ruby:</p><h4>Inside the class definition</h4><ol><li>Using the keyword self with the name of the method:</li></ol><pre>class MathFunctions<br>  def self.two_times(num)<br>    num * 2<br>  end<br>end</pre><pre># <em>No instance created<br></em>puts MathFunctions.two_times(10) # =&gt; <em>20</em></pre><p>2. Using &lt;&lt; self</p><pre>class MathFunctions<br>  class &lt;&lt; self<br>    def two_times(num)<br>      num * 2<br>    end<br>  end<br>end</pre><pre># <em>No instance created<br></em>puts MathFunctions.two_times(10) # =&gt; <em>20</em></pre><h4>Outside the class definition</h4><p>3. Using class name with the method name</p><pre>class MathFunctions<br>end</pre><pre>def MathFunctions.two_times(num)<br>  num * 2<br>end</pre><pre># <em>No instance created<br></em>puts MathFunctions.two_times(10) # =&gt; <em>20</em></pre><h3>Class Inheritance</h3><p>In Ruby, every class implicitly inherits from the Object class. Let’s look at an example.</p><pre>class Car<br>  def to_s<br>    &quot;Car&quot;<br>  end</pre><pre>  def speed<br>    &quot;Top speed 100&quot;<br>  end<br>end</pre><pre>class SuperCar &lt; Car<br>  def speed # <em>Override</em><br>    &quot;Top speed 200&quot;<br>  end<br>end</pre><pre>car = Car.new<br>fast_car = SuperCar.new</pre><pre>puts &quot;#{car}1 #{car.speed}&quot; # =&gt; <em>Car1 Top speed 100</em><br>puts &quot;#{fast_car}2 #{fast_car.speed}&quot; # =&gt; <em>Car2 Top speed 200</em></pre><p>In the above example, the SuperCar class overrides the speed method which is inherited from the Car class. The symbol &lt; denotes inheritance.</p><p><em>Note: Ruby doesn’t support multiple inheritance, and so mix-ins are used instead. We will discuss them later in this article.</em></p><h3>Modules in Ruby</h3><p>A Ruby module is an important part of the Ruby programming language. It’s a major object-oriented feature of the language and supports multiple inheritance indirectly.</p><p>A module is a container for classes, methods, constants, or even other modules. Like a class, a module cannot be instantiated, but serves two main purposes:</p><ul><li>Namespace</li><li>Mix-in</li></ul><h4>Modules as Namespace</h4><p>A lot of languages like Java have the idea of the package structure, just to avoid collision between two classes. Let’s look into an example to understand how it works.</p><pre>module Patterns<br>  class Match<br>    attr_accessor :matched<br>  end<br>end</pre><pre>module Sports<br>  class Match<br>    attr_accessor :score<br>  end<br>end</pre><pre>match1 = Patterns::Match.new<br>match1.matched = &quot;true&quot;</pre><pre>match2 = Sports::Match.new<br>match2.score = 210</pre><p>In the example above, as we have two classes named Match, we can differentiate between them and prevent collision by simply encapsulating them into different modules.</p><h4>Modules as Mix-in</h4><p>In the object-oriented paradigm, we have the concept of Interfaces. Mix-in provides a way to share code between multiple classes. Not only that, we can also include the built-in modules like Enumerable and make our task much easier. Let’s see an example.</p><pre>module PrintName<br>  attr_accessor :name<br>  def print_it<br>    puts &quot;Name: #{@name}&quot;<br>  end<br>end</pre><pre>class Person<br>  include PrintName<br>end</pre><pre>class Organization<br>  include PrintName<br>end</pre><pre>person = Person.new<br>person.name = &quot;Nishant&quot;<br>puts person.print_it # =&gt; <em>Name: Nishant</em></pre><pre>organization = Organization.new<br>organization.name = &quot;freeCodeCamp&quot;<br>puts organization.print_it # =&gt; <em>Na</em>me: freeCodeCamp </pre><p>Mix-ins are extremely powerful, as we only write the code once and can then include them anywhere as required.</p><h3>Scope in Ruby</h3><p>We will see how scope works for:</p><ul><li>variables</li><li>constants</li><li>blocks</li></ul><h4>Scope of variables</h4><p>Methods and classes define a new scope for variables, and outer scope variables are not carried over to the inner scope. Let’s see what this means.</p><pre>name = &quot;Nishant&quot;</pre><pre>class MyClass<br>  def my_fun<br>    name = &quot;John&quot;<br>    puts name # =&gt; <em>John<br>  </em>end</pre><pre>puts name # =&gt; <em>Nishant</em></pre><p>The outer name variable and the inner name variable are not the same. The outer name variable doesn’t get carried over to the inner scope. That means if you try to print it in the inner scope without again defining it, an exception would be thrown — <strong>no such variable exists</strong></p><h4>Scope of constants</h4><p>An inner scope can see constants defined in the outer scope and can also override the outer constants. But it’s important to remember that even after overriding the constant value in the inner scope, the value in the outer scope remains unchanged. Let’s see it in action.</p><pre>module MyModule<br>  PI = 3.14<br>  class MyClass<br>    def value_of_pi<br>      puts PI # =&gt; <em>3.14<br>      </em>PI = &quot;3.144444&quot;<br>      puts PI # =&gt; <em>3.144444<br>    </em>end<br>  end<br>  puts PI # =&gt; <em>3.14<br></em>end</pre><h4>Scope of blocks</h4><p>Blocks inherit the outer scope. Let’s understand it using a fantastic example I found on the internet.</p><pre>class BankAccount<br>  attr_accessor :id, :amount<br>  def initialize(id, amount)<br>    @id = id<br>    @amount = amount<br>  end<br>end</pre><pre>acct1 = BankAccount.new(213, 300)<br>acct2 = BankAccount.new(22, 100)<br>acct3 = BankAccount.new(222, 500)</pre><pre>accts = [acct1, acct2, acct3]</pre><pre>total_sum = 0<br>accts.each do |eachAcct|<br>  total_sum = total_sum + eachAcct.amount<br>end</pre><pre>puts total_sum # =&gt; <em>900</em></pre><p>In the above example, if we use a method to calculate the total_sum, the total_sum variable would be a totally different variable inside the method. That’s why sometimes using blocks can save us a lot of time.</p><p>Having said that, a variable created inside the block is only available to the block.</p><h3>Access Control</h3><p>When designing a class, it is important to think about how much of it you’ll be exposing to the world. This is known as <strong>Encapsulation,</strong> and typically means hiding the internal representation of the object.</p><p>There are three levels of access control in Ruby:</p><ul><li><strong>Public</strong> - no access control is enforced. Anybody can call these methods.</li><li><strong>Protected</strong> - can be invoked by objects of the defining classes or its sub classes.</li><li><strong>Private</strong> - cannot be invoked except with an explicit receiver.</li></ul><p>Let’s see an example of Encapsulation in action:</p><pre>class Car<br>  def initialize(speed, fuel_eco)<br>    @rating = speed * comfort<br>  end</pre><pre>  def rating<br>    @rating<br>  end<br>end</pre><pre>puts Car.new(100, 5).rating # =&gt; <em>500</em></pre><p>Now, as the details of how the rating is calculated are kept inside the class, we can change it at any point in time without any other change. Also, we cannot set the rating from outside.</p><p>Talking about the ways to specify access control, there are two of them:</p><ol><li>Specifying public, protected, or private and everything until the next access control keyword will have that access control level.</li><li>Define the method regularly, and then specify public, private, and protected access levels and list the comma(,) separated methods under those levels using method symbols.</li></ol><h4>Example of the first way:</h4><pre>class MyClass<br>  private<br>    def func1<br>      &quot;private&quot;<br>    end<br>  protected<br>    def func2<br>      &quot;protected&quot;<br>    end<br>  public<br>    def func3<br>      &quot;Public&quot;<br>    end<br>end</pre><h4>Example of the second way:</h4><pre>class MyClass<br>  def func1<br>    &quot;private&quot;<br>  end<br>  def func2<br>    &quot;protected&quot;<br>  end<br>  def func3<br>    &quot;Public&quot;<br>  end<br>  private :func1<br>  protected :func2<br>  public :func3<br>end</pre><p><em>Note: The public and private access controls are used the most.</em></p><h3>Conclusion</h3><p>These are the very basics of Object Oriented Programming in Ruby. Now, knowing these concepts you can go deeper and learn them by building cool stuff.</p><p>Don’t forget to clap and follow if you enjoyed! Keep up with me <a href="https://www.instagram.com/nishantmishra02/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73531e2b8ddc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/an-introduction-to-object-oriented-programming-with-ruby-73531e2b8ddc">An Introduction to Object-Oriented Programming with Ruby</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>