<?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 Abhishek Tanwar on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Tanwar on Medium]]></description>
        <link>https://medium.com/@abhishektanwar9596?source=rss-737d2a275faa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e_fIUDxMIZ23f0W5gWRcPA.jpeg</url>
            <title>Stories by Abhishek Tanwar on Medium</title>
            <link>https://medium.com/@abhishektanwar9596?source=rss-737d2a275faa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:20:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishektanwar9596/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[Decorator Design Pattern in Rails.]]></title>
            <link>https://medium.com/@abhishektanwar9596/decorator-design-pattern-in-rails-a8fcdb6c6780?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8fcdb6c6780</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 04:10:06 GMT</pubDate>
            <atom:updated>2024-01-27T04:10:06.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decorator Design Pattern in Rails:</h3><p>In Ruby on Rails, the decorator design pattern is a structural pattern that allows you to add behaviour or responsibilities to objects dynamically. Decorators are used to wrap objects and extend their functionalities without altering their structure. They provide a flexible alternative to sub-classing for extending functionality.</p><p>One popular solution that can get you started quickly is <a href="https://github.com/drapergem/draper">Draper gem</a>. With it,</p><p><strong>How is it different from rails helpers?</strong></p><p>The key difference between decorators and helpers lies in their purpose and usage. Decorators are focused on extending and modifying the behavior of objects, while helpers are more about providing utility methods for use in views. Decorators are typically used to enhance the individual instances of objects, while helpers are more about providing general-purpose functionality across the application.</p><h3>Example:</h3><p>Let’s consider a simple example with a Book model. We want to display a formatted title in a view.</p><h4>Using Decorator:</h4><pre># app/decorators/book_decorator.rb<br>class BookDecorator<br>  def initialize(book)<br>    @book = book<br>  end<br><br>  def formatted_title<br>    &quot;Title: #{title_case(@book.title)}&quot;<br>  end<br><br>  private<br><br>  def title_case(title)<br>    # Some logic to format title as title case<br>  end<br>end<br><br># app/views/books/show.html.erb<br>&lt;%= BookDecorator.new(@book).formatted_title %&gt;</pre><h4>Using Helper:</h4><pre># app/helpers/books_helper.rb<br>module BooksHelper<br>  def formatted_title(book)<br>    &quot;Title: #{title_case(book.title)}&quot;<br>  end<br><br>  private<br><br>  def title_case(title)<br>    # Some logic to format title as title case<br>  end<br>end<br><br># app/views/books/show.html.erb<br>&lt;%= formatted_title(@book) %&gt;</pre><p>In this example, the decorator pattern provides a dedicated class (BookDecorator) for handling the presentation logic of the Book model. This can lead to cleaner, more maintainable code as the application grows, compared to incorporating everything into a helper module.</p><p>While helpers are perfectly suitable for certain scenarios, decorators shine in situations where you want a more structured and testable way to enhance the behavior or presentation of individual objects. The choice between decorators and helpers depends on the specific needs and complexity of your application.</p><p>Resources:</p><ul><li>ChatGPT</li><li><a href="https://github.com/drapergem/draper">Official Ruby on Rails Blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8fcdb6c6780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why do we need strong parameters in rails?]]></title>
            <link>https://medium.com/@abhishektanwar9596/why-do-we-need-strong-parameters-in-rails-430b9f5f1410?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/430b9f5f1410</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 06:19:04 GMT</pubDate>
            <atom:updated>2024-01-04T06:19:04.287Z</atom:updated>
            <content:encoded><![CDATA[<p>In Ruby on Rails, “strong parameters” refers to a security feature that helps protect your application against mass assignment vulnerabilities. Mass assignment is a way to update or create multiple attributes of a model with a single request, and it can be a security risk if not handled properly.</p><p>Here’s a simple scenario without strong parameters:</p><pre># In the controller<br>class UsersController &lt; ApplicationController<br>  def create<br>    # Vulnerable to mass assignment<br>    @user = User.new(params[:user])<br>    @user.save<br>    # ...<br>  end<br>end</pre><p>In this example, a user creation action (create) attempts to create a new User instance using the parameters directly from the request (params[:user]). If there are no restrictions in place, an attacker could potentially include additional parameters in the request, like admin: true, even if the form or the intended request didn&#39;t include a field for admin. This would result in the user being created with administrative privileges unintentionally.</p><p>Consider a scenario where you have a User model with attributes like username, email, and admin. If you allow mass assignment without any restrictions, a malicious user could submit a request with additional parameters, like admin: true, even if your form or intended update action didn&#39;t provide a field for the admin attribute.</p><p>To mitigate this type of attack, Rails introduced strong parameters, which require you to explicitly whitelist the parameters that are allowed to be updated or created. This is typically done in the controller to ensure that only the intended attributes can be modified.</p><p>Here’s a simple example:</p><pre>class UsersController &lt; ApplicationController<br>  def update<br>    @user = User.find(params[:id])<br>    @user.update(user_params)<br>    # ...<br>  end<br><br>  private<br><br>  def user_params<br>    params.require(:user).permit(:username, :email)<br>  end<br>end</pre><p>In this example, user_params is a private method that uses the require and permit methods from the params object. The require(:user) ensures that the request parameters must contain a user key, and permit(:username, :email) specifies which attributes are allowed to be updated.</p><p>By using strong parameters, you enhance the security of your Rails application by preventing unwanted or malicious updates to your models. It helps ensure that only the explicitly permitted attributes are allowed to be mass-assigned, protecting your application from potential security vulnerabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=430b9f5f1410" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Annotate Gem in Rails: Documenting Your Database Schema]]></title>
            <link>https://medium.com/@abhishektanwar9596/a-guide-to-annotate-gem-in-rails-documenting-your-database-schema-ed10265f1ab3?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed10265f1ab3</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 07:07:53 GMT</pubDate>
            <atom:updated>2023-12-26T07:07:53.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the world of Rails development, maintaining up-to-date database schema documentation is crucial for collaboration and codebase understanding. The annotate gem provides a convenient way to automatically add comments with the schema information directly into your ActiveRecord model files. This guide will walk you through the process of installing and using the annotate gem in your Rails application.</p><h3>Step 1: Installation</h3><p>Start by adding the annotate gem to your Rails project&#39;s Gemfile:</p><pre># Gemfile<br><br>group :development, :test do<br>  gem &#39;annotate&#39;<br>end</pre><p>Then, run the bundle install command:</p><pre>bundle install</pre><p><em>or simply, you can add a gem by running this command:</em></p><pre>bundle add &#39;annotate&#39;</pre><h3>Step 2: Configuration</h3><p>After installing the gem, you need to configure it to run automatically after migrations. Create a file named config/application.rb if it doesn&#39;t exist, add the following lines:</p><pre># config/application.rb<br><br>module YourAppName<br>  class Application &lt; Rails::Application<br>    # Other configurations<br><br>    # Automatically annotate models after migrations<br>    config.after_initialize do<br>      require &#39;annotate&#39;<br>      Annotate.load_tasks<br>      AnnotateTask.new.invoke(&#39;models&#39;)<br>    end<br>  end<br>end</pre><p>This configuration ensures that the annotations are updated each time you run migrations.</p><h3>Step 3: Run Annotations</h3><p>Now, you can run the annotations task to add comments to your models. Open a terminal and run the following command:</p><pre>rails annotate</pre><p>This command will analyze your database schema and add comments to the corresponding ActiveRecord model files.</p><h3>Step 4: Customize Annotations (Optional)</h3><p>The annotate gem provides various options to customize the generated annotations. You can include or exclude specific file patterns, customize the format of the annotations, and more. Refer to the gem&#39;s documentation for a comprehensive list of options: <a href="https://github.com/ctran/annotate_models"><em>annotate gem documentation.</em></a></p><h3>Conclusion</h3><p>Congratulations! You’ve successfully integrated the annotate gem into your Rails application, making it easier to keep your database schema documentation up-to-date. As your application evolves and your database schema changes, running rails annotate will ensure that your ActiveRecord models reflect the latest database structure.</p><p>Remember to commit the changes to your version control system so that the annotations stay synchronized with your codebase. With well-documented models, your development team will find it easier to understand and work with the database schema.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed10265f1ab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between “validate” and “validates” in the rails model?]]></title>
            <link>https://medium.com/@abhishektanwar9596/what-is-the-difference-between-validate-and-validates-in-the-rails-model-fc1ed7311b83?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc1ed7311b83</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 06:18:05 GMT</pubDate>
            <atom:updated>2023-12-26T06:18:05.658Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends, In Ruby on Rails, the terms “validate” and “validates” refer to different aspects of the validation process in a model.</p><ol><li>validate (singular):</li><li>validates (plural):</li></ol><p>validate (singular):</p><ul><li>The validate method in a Rails model is used to specify custom validation methods.</li><li>When you use validate, you are telling Rails to call a specific method (or multiple methods) during the validation process. These custom validation methods are responsible for checking the validity of the model&#39;s data based on your custom criteria.</li><li>Example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*2LknfjH4hPY64Gc2dOmUEQ.png" /></figure><p>validates (plural):</p><ul><li>The validates method is used to apply built-in validation rules to model attributes.</li><li>With validates, you can specify rules such as presence, length, numericality, and more for individual attributes of the model.</li><li>Example:</li></ul><pre>class MyModel &lt; ApplicationRecord<br>  validates :name, presence: true<br>  validates :email, uniqueness: true, format: { with: /\A[^@\s]+@[^@\s]+\z/ }<br>end</pre><p><strong><em>In summary, </em></strong><strong><em>validate is used to define custom validation methods, while </em></strong><strong><em>validates is used to apply built-in validation rules to model attributes. Both are essential for ensuring the integrity of data in your Rails application.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc1ed7311b83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WHAT IS THE DIFFERENCE BETWEEN A PLUGIN AND A GEM in Ruby on Rails?]]></title>
            <link>https://medium.com/@abhishektanwar9596/what-is-the-difference-between-a-plugin-and-a-gem-in-ruby-on-rails-c2cabcf5103d?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2cabcf5103d</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 18:11:01 GMT</pubDate>
            <atom:updated>2023-03-22T18:11:01.457Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends, today i am going to explain about plugin vs gem,</p><p>A gem is just ruby code, it is installed on a machine and will be available for all ruby applications running on that machine. as rake files.</p><p>A plugin also ruby code, but it is installed in the application folder and only available for that specific application.</p><p>Sitemap-generator, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2cabcf5103d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is attr_accessor in Ruby?]]></title>
            <link>https://medium.com/@abhishektanwar9596/what-is-attr-accessor-in-ruby-6af3f5bdfce6?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6af3f5bdfce6</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 18:04:48 GMT</pubDate>
            <atom:updated>2023-03-22T18:04:48.361Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello guys, this is Abhishek Tanwar, now i am going to explain about attr_accessor —</p><p>Simply attr-accessor creates the getter and setter methods for the specified attributes</p><p>Here getter is nothing but is used to fetch the variable whereas the setter is used to assign the value to that variable example:</p><pre>class Demo<br>  attr_accessor :name<br>end</pre><p>object = Demo.new</p><p>object.name = “I am learning Ruby On rails”</p><p>object. name =&gt; “I am learning Ruby On rails”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6af3f5bdfce6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Rails Concerns Work and How to Use Them?]]></title>
            <link>https://medium.com/@abhishektanwar9596/how-rails-concerns-work-and-how-to-use-them-c71d42612808?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c71d42612808</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Sun, 29 May 2022 08:56:57 GMT</pubDate>
            <atom:updated>2022-05-29T08:56:57.904Z</atom:updated>
            <content:encoded><![CDATA[<p>A Rails <a href="https://api.rubyonrails.org/classes/ActiveSupport/Concern.html">Concern</a> is a module that extends the ActiveSupport::Concern module. Concerns allow us to include modules with methods (both instance and class) and constants into a class so that the including class can use them.</p><ol><li><em>included</em></li></ol><ul><li>The code inside the included block is evaluated in the context of the including class. For example, if Post includes a concern, anything inside the included block will be evaluated as if it was written inside Post.</li><li>You can write class macros (validations, associations, scopes, etc.) here, and any methods become instance methods of the including class.</li></ul><p><em>2</em></p><p><em>class_methods</em></p><ul><li>The methods added inside this block become the class methods on the including class.</li><li>Instead of the class_methods block, you can create a nested module named ClassMethods.</li></ul><p>Here’s a concern named <strong>Taggable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*ZU2CHfSpi4Y3n_gLxtbHxQ.png" /></figure><blockquote><strong><em>When we should go for Concern?</em></strong></blockquote><p>According to the Rails docs, we want to encapsulate the code in a different module to reuse that code in different places when that same functionality is needed. We use concerns <strong>when we feel that one file is overwhelmed with the functionality</strong>, so we extract some part of the code and save it into another file or module.</p><h3>How do you use concerns?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*sDffe0EQyBKt8e4vxKEeHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*plaLHinTYk94_-bVVKdZIQ.png" /><figcaption>To use this concern, you include the module as usual. For example, if the Post model wanted the visibility functionality, it would include the Visible concern.</figcaption></figure><h3>Rails routes concerns:</h3><p>We can use Routing concerns, to avoid repeating same routes defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*AqiHA28I195W1Lbj5WOsIw.png" /></figure><h3>Multiple concerns in routes:</h3><p>We can have multiple concerns, used for a resource or resources.</p><p>Let’s say, we have imageable and commentable concerns as given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*JptIh6J_LmZ20CUD1wLnnA.png" /></figure><h3>References</h3><ul><li><a href="https://guides.rubyonrails.org/routing.html">Rails Routes</a></li><li><a href="https://rubyinrails.com/2014/12/14/ruby-flay-gem-dry-codebase/">DRY</a></li><li><a href="https://edgeguides.rubyonrails.org/routing.html#routing-concerns">Routing Concerns in Rails</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c71d42612808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s a ViewComponent?]]></title>
            <link>https://medium.com/@abhishektanwar9596/whats-a-viewcomponent-42b6f7e24321?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/42b6f7e24321</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Sun, 29 May 2022 08:56:13 GMT</pubDate>
            <atom:updated>2022-05-29T08:56:13.174Z</atom:updated>
            <content:encoded><![CDATA[<p>A framework for creating reusable, testable &amp; encapsulated view components, built to integrate seamlessly with Ruby on Rails.</p><p>Think of ViewComponents as an evolution of the presenter pattern, inspired by <a href="https://reactjs.org/docs/react-component.html">React</a>. A ViewComponent is a Ruby object and template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*UHjPRU-tBs3Q4TXnRO-rVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*0YzNLsKxZmxTI6XLRSVWxw.png" /></figure><p>Which is instantiated and passed to Rails’ #render:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*rqCDsb3LHX-O_LbhXu1lvA.png" /></figure><p>Returning markup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*SuOmO9cshBUtt_F0nCHCyw.png" /></figure><h3>Why use ViewComponents?</h3><p>There are so many crucial reasons for to use it,</p><ol><li>ViewComponents are ~10x faster than partials in real-world use-cases.</li><li>ViewComponents are Ruby objects, making it easy to follow (and enforce) code quality standards.</li><li>Rails applications often scatter view-related logic across models, controllers, and helpers, diluting their intended responsibilities. ViewComponents consolidate the logic needed for a template into a single class, resulting in a cohesive object that is easy to understand.</li></ol><p>Reference:</p><p><a href="https://viewcomponent.org/">official documentaion</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b6f7e24321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use yield within a class in ruby?]]></title>
            <link>https://medium.com/@abhishektanwar9596/how-to-use-yield-within-a-class-in-ruby-c1ed61b4b431?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1ed61b4b431</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 04:53:53 GMT</pubDate>
            <atom:updated>2021-12-06T04:53:53.768Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello guys, in this article i am going to explain how to use yield within a class , we have seen many example like as —</p><pre>def test<br>   puts &quot;You are in the method&quot;<br>   yield<br>   puts &quot;You are again back to the method&quot;<br>   yield<br>end<br>test {puts &quot;You are in the block&quot;}</pre><p>but i have not seen how to use yield within a class, many guys encountered this, that’s why i tried for it , any suggestions or criticism are welcomed,</p><p>this is what i have tried</p><pre>class Demo<br>    def self.check_box_tag<br>        yield<br>    end<br>    check_box_tag{ puts &quot;hello&quot;}<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1ed61b4b431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bang methods in ruby]]></title>
            <link>https://medium.com/@abhishektanwar9596/bang-methods-in-ruby-c4f3a069e287?source=rss-737d2a275faa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f3a069e287</guid>
            <dc:creator><![CDATA[Abhishek Tanwar]]></dc:creator>
            <pubDate>Tue, 12 Oct 2021 13:14:13 GMT</pubDate>
            <atom:updated>2021-10-12T13:14:13.021Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll look at what bang methods are and how they work.</p><p>This article is divided into the following sections:</p><ol><li>What are bang methods in ruby</li><li>Bang method must return a modified object</li><li>Bang methods can return nil</li><li>Usually, bang method has its non-bang equivalent</li><li>Summary</li></ol><h3>What are bang methods in ruby</h3><p>Methods that end with the exclamation mark, for example, downcase! or compact! are called <strong>bang methods</strong> ( also mutator methods, dangerous methods). The usual methods perform an action on a copy of the object and then return copy, bang methods — perform an action and change the object, returning the modified object as a result. Sometimes this is called a ‘mutation’ of the object. The exclamation mark, in this case, is usually associated with an attempt to send the message: “Warning! This method can be dangerous! It will change the value of the object!”</p><h3>Bang method must return a modified object</h3><p>If we put the exclamation mark at the end of the method, our method, of course, will not work as a bang method. In order for our method to conform to the convention, it must return the same object that was changed. You can easily achieve this in ruby, it’s enough to use another bang method for this.</p><p>For instance:</p><pre>class ExampleClass <br>  <br>  attr_accessor :number<br>  <br>  def remove_whitespace! <br>    @number.strip!<br>  endend a = ExampleClass.new <br>a.number = &quot;    green&quot;<br>puts a.number <br>puts &quot;----------------&quot;<br>puts a.remove_whitespace! <br>puts &quot;----------------&quot;<br>puts a.number</pre><p>produces:</p><pre>green<br>----------------<br>green<br>----------------<br>green<br>=&gt; nil</pre><p>As we can see, the value of the instance variable @number has changed. However, there is a small problem here. Although we see that the value has changed, this may not be enough to say is this the same object or not. Quite often it’s visually impossible to understand which object is in front of you, especially if we have a fairly large method, and then the ‘object_id’ method comes to the rescue.</p><p>This method is defined in the Object class that makes it available to all ruby objects. The job of this method is to tell us which object id has the object.</p><p>For instance, we have the following code:</p><pre>puts &quot;---------------&quot;<br>a = &quot;123&quot;<br>puts a.object_id<br>puts &quot;---------------&quot;<br>a = &quot;123&quot;<br>puts a.object_id<br>puts &quot;---------------&quot;</pre><p>produces:</p><pre>---------------<br>47353786377940<br>---------------<br>47353789471600<br>---------------<br>=&gt; nil</pre><p>As you can see, we have 2 visually identical objects, but they have different object ids, which tells us that these objects are different and that they are stored in different places.</p><p>Now, let’s try another example. In the new example, we will extend the String class and add the change_color! method which will use the gsub! method for changing object’s value.</p><pre>class String <br>  <br>  def change_color!<br>    self.gsub!(/yellow/, &quot;red&quot;)<br>  end<br>  <br>end a = &quot;yellow submarine&quot;<br>puts &quot;Initial value of a: #{a}&quot;<br>puts &quot;Object id of &#39;a&#39;: #{a.object_id}&quot;<br>a.change_color!<br>puts &quot;Object id of &#39;a&#39;: #{a.object_id}&quot;<br>puts &quot;Value of &#39;a&#39;: #{a}&quot;</pre><p>produces:</p><pre>Initial value of a: yellow submarine<br>Object id of &#39;a&#39;: 47290541645240<br>Object id of &#39;a&#39;: 47290541645240<br>Value of &#39;a&#39;: red submarine<br>=&gt; nil</pre><p>As you can see, we changed the value of the object and it has the same object id in both cases.</p><h3>Bang methods can return nil</h3><p>A lot of bang methods have a distinctive feature. If they don’t change the object, they return nil.</p><p>For instance:</p><pre>puts &#39;cat&#39;.upcase! <br>puts &#39;CAT&#39;.upcase!</pre><p>produces:</p><pre>CAT=&gt; nil</pre><p>As you can see, in the second case we got nil as the returned value. This is because in the string ‘CAT’ all the characters already were written in the upper case and the method upcase! doesn’t know what to do. That’s why there are can be situations when in a conditional expression you get nil and the condition will be work in an unexpected way.</p><p>For instance:</p><pre>cat_name = &quot;CAT&quot;<br>formatted_cat_name = cat_name.upcase!if formatted_cat_name <br>  puts &quot;Hi #{formatted_cat_name}! Kitty! Kitty! Kitty!&quot;<br>else <br>  puts &quot;Kitty! Kitty! Kitty!&quot;<br>end</pre><p>produces:</p><pre>Kitty! Kitty! Kitty!<br>=&gt; nil</pre><p>As you can see, despite the fact that we have a cat’s name, we can’t normally say hello :) Thus, if you need to get exactly true or false then you should think about scenarios when you will get nil instead of something that will be evaluated as true.</p><h3>Usually, bang method has its non-bang equivalent</h3><p>For example, the following methods are defined in the String class:</p><pre>:upcase, :upcase!, :downcase, :downcase!, :capitalize, :capitalize!, :swapcase, :swapcase!</pre><p>Let’s use those methods:</p><pre>a = &quot;first string&quot;<br>a.upcase<br>puts &quot;Object id of &#39;a&#39;: #{a.object_id}&quot;<br>a.upcase!<br>puts &quot;Object id of &#39;a&#39;: #{a.object_id}&quot;<br>puts a b = &quot;SECOND STRING&quot;<br>b.downcase<br>puts &quot;Object id of &#39;b&#39;: #{b.object_id}&quot;<br>b.downcase!<br>puts &quot;Object id of &#39;b&#39;: #{b.object_id}&quot;<br>puts b c = &quot;third string&quot;<br>c.capitalize<br>puts &quot;Object id of &#39;c&#39;: #{c.object_id}&quot;<br>c.capitalize!<br>puts &quot;Object id of &#39;c&#39;: #{c.object_id}&quot;<br>puts c</pre><p>produces:</p><pre>Object id of &#39;a&#39;: 47254336344720<br>Object id of &#39;a&#39;: 47254336344720<br>FIRST STRING<br>Object id of &#39;b&#39;: 47254336341460<br>Object id of &#39;b&#39;: 47254336341460<br>second string<br>Object id of &#39;c&#39;: 47254336315140<br>Object id of &#39;c&#39;: 47254336315140<br>Third string<br>=&gt; nil</pre><h3>Summary</h3><ul><li>according to the convention if your method changes the object value (mutates object) then it must end with the exclamation mark;<br>- bang methods can return nil;<br>- you can determine whether the method is a beng method using the object_id method;<br>- a lot of bang methods has its non-bang equivalents.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f3a069e287" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>