<?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 Sai Krishna Prasad on Medium]]></title>
        <description><![CDATA[Stories by Sai Krishna Prasad on Medium]]></description>
        <link>https://medium.com/@krrish96?source=rss-f6683703c844------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HGBwGSyhmXoRbJGmrzsdzg.jpeg</url>
            <title>Stories by Sai Krishna Prasad on Medium</title>
            <link>https://medium.com/@krrish96?source=rss-f6683703c844------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:50:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krrish96/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[How to Smoothly Render Images in React App?]]></title>
            <link>https://medium.com/@krrish96/how-to-smoothly-render-images-in-react-app-3110b9de15c9?source=rss-f6683703c844------2</link>
            <guid isPermaLink="false">https://medium.com/p/3110b9de15c9</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sai Krishna Prasad]]></dc:creator>
            <pubDate>Mon, 09 Mar 2020 05:01:35 GMT</pubDate>
            <atom:updated>2020-03-10T07:10:33.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Smooth Image Rendering with react and SCSS — reander-smooth-image-react" src="https://cdn-images-1.medium.com/max/1024/1*TiRv3T_l97j42do3Wr63zA.png" /><figcaption>Smooth Image Rendering with react and SCSS</figcaption></figure><h4>Improve your web apps UX by enhancing image render with React’s onLoad event and simple SCSS</h4><blockquote>This article is cross-posted on <a href="https://codebrahma.com/how-to-smoothly-render-images-in-react-app/">Codebrahma</a> and <a href="https://dev.to/krrish96/how-to-smoothly-render-images-in-react-app-201j">Dev.to</a></blockquote><p>Let’s cut to the chase. The GIF below shows what we are going to achieve by the end of this post.</p><figure><img alt="Demo GIF comparing default image rendering with smooth image rendering using render-smooth-image-react" src="https://cdn-images-1.medium.com/max/600/1*Bv__UK8VzhnHev9T2865qg.gif" /><figcaption>Default Image Rendering vs Smooth Image Rendering using <a href="https://www.npmjs.com/package/render-smooth-image-react"><strong>render-smooth-image-react</strong></a></figcaption></figure><p>Here is the Completed Component — RenderSmoothImage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0fdc77a5409edeecaae7d6ddd5b64d2/href">https://medium.com/media/e0fdc77a5409edeecaae7d6ddd5b64d2/href</a></iframe><p>I have published this as an npm package <a href="https://www.npmjs.com/package/render-smooth-image-react">render-smooth-image-react</a>. The source code is available on <a href="https://github.com/KRRISH96/render-smooth-image-react">GitHub</a>.</p><h3>Little Back Story</h3><p>I recently started working on a media-heavy app. Everything was cool until I noticed a bunch of images rendering poorly. Which looked something like this.</p><figure><img alt="Example: Poor image rendering (printing)" src="https://cdn-images-1.medium.com/max/300/1*HNHzk5zPJeOjUSRAoGc2jw.gif" /><figcaption>Example: Poor image rendering (printing)</figcaption></figure><p>For a moment I thought, “Did I end up building a 🖨 <em>printer simulator app</em>?”</p><p>Overall customer satisfaction will take a hit with such poor loading UX (even if the rest of the app is great). This is especially true for media-heavy apps.</p><p>Alright, Let’s see what we can do to fix this.</p><h3>Load and Fire 🔫</h3><blockquote><em>Let the browser download the image and render it.</em></blockquote><p>The perfect moment to render an image is after downloading completely. Till then we just show a loader/placeholder and hide the image.</p><p>We can achieve this by using React’s <a href="https://reactjs.org/docs/events.html#image-events">onLoad</a> event on the image tag. You can read more about <a href="https://reactjs.org/">React.js</a> events <a href="https://reactjs.org/docs/events.html">here</a>.</p><pre>&lt;img onLoad={&#39;callbackAfterImageIsDownloaded&#39;} /&gt;</pre><h3>Code it</h3><p>We will create a functional component and use hooks to maintain a couple of states. If you are new to React Hooks, You can learn more <a href="https://reactjs.org/docs/hooks-intro.html">here</a>.</p><pre>// RenderSmoothImage.js<br>function RenderSmoothImage({src, alt}) {<br>  const [imageLoaded, setImageLoaded]=React.useState(false);</pre><pre>return (<br>    &lt;div className=&quot;smooth-image-wrapper&quot;&gt;<br>      &lt;img<br>        src={src}<br>        alt={alt}<br>     <strong>   </strong>className={`smooth-image image-${imageLoaded ? &#39;visible&#39; :  &#39;hidden&#39;}`}<br>        onLoad={()=&gt; setImageLoaded(true)}}<br>      /&gt;<br>      {!imageLoaded &amp;&amp; (<br>        &lt;div className=&quot;smooth-preloader&quot;&gt;<br>          &lt;span className=&quot;loader&quot; /&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  )<br>}</pre><pre><br>// styles<br>.smooth-image {<br>  transition: opacity 1s; <br>}<br>.image-visible {opacity: 1}<br>.image-hidden {opacity: 0}</pre><p>Here, we maintain a state imageLoaded defaults to false. Which will then be set to true, once the image is downloaded. We use the onLoad event to trigger this.</p><p>Then we use imageLoaded state to conditionally add classes to the img tag, <strong>image-visible </strong>vs<strong> image-hidden</strong>. We can add transitions/animations to make it smoother. Please refer to the linked Gist at the top for complete styles.</p><p>That’s it! No more printer simulators on the page.</p><h3>What if Image Download Fails / Invalid Src?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*wkO81KDsMbzOCYpXn6bPxg.png" /><figcaption>Image for alternate text with image tag</figcaption></figure><p>By using the alt attribute we can show alternate text for the image. However, the default icon and styling isn’t too great. To fix this we can display custom alt text.</p><pre>// RenderSmoothImage.js<br>function RenderSmoothImage({src, alt}) {<br>  .....<br>  const [isValidSrc, setIsValidSrc] = React.useState(!!src);</pre><pre>return (<br>    &lt;div className=&quot;smooth-image-wrapper&quot;&gt;<br>      {isValidSrc ? (<br>        &lt;img<br>     <strong>     ....<br>          onError={() =&gt; setIsValidSrc(false)}</strong><br>        /&gt;<br>      ) : (<br>        &lt;div className=&quot;smooth-no-image&quot;&gt;{alt}&lt;/div&gt;<br>      )}<br>      {isValidSrc &amp;&amp; !imageLoaded &amp;&amp; (<br>        &lt;div className=&quot;smooth-preloader&quot;&gt;<br>          &lt;span className=&quot;loader&quot; /&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>// styles<br>......<br>.smooth-no-image {<br>  background-image: linear-gradient(90deg,#ccc,#999,#ccc);<br>  color: #fff;<br>}</pre><p>There you go,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*OGOysRrwqDr4u5tvruXwwQ.png" /><figcaption>Customized Alternate Text for Image</figcaption></figure><p>You can style the Alternative text any way you want.</p><p>I made things easy for you and published a light-weight npm package <a href="https://www.npmjs.com/package/render-smooth-image-react">render-smooth-image-react</a>.</p><p><a href="https://www.npmjs.com/package/render-smooth-image-react">render-smooth-image-react</a></p><p>Thank you for reading this post, This is <a href="https://www.linkedin.com/in/kskp1996">Sai Krishna Prasad</a>, a self-taught and passionate web developer. Signing off Bubye….. until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3110b9de15c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Procs, Lambdas, and Blocks in Ruby.]]></title>
            <link>https://medium.com/@krrish96/understanding-procs-lambdas-and-blocks-in-ruby-part-2-all-whys-explained-f6e46944356f?source=rss-f6683703c844------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6e46944356f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Sai Krishna Prasad]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 12:48:00 GMT</pubDate>
            <atom:updated>2020-02-24T12:48:00.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Ruby Procs, Lambdas and Blocks. 2. All Why?s Explained" src="https://cdn-images-1.medium.com/max/1024/1*smPxYvaSc8eWpcFACGxwYQ.png" /><figcaption>Procs, Lambdas, and Blocks in Ruby</figcaption></figure><h4>Part 2: All Why?s Explained.</h4><p>In the first part of this article, We learned about what Procs, Lambdas, and Blocks are? If you haven’t read it, I strongly recommend you to read <a href="https://medium.com/@krrish96/understanding-procs-lambdas-and-blocks-in-ruby-part-1-all-whats-answered-db91f30aab54">Part 1: All what?s Answered</a>, before continuing.</p><figure><img alt="Meme: Spider Man asking “Cool Story, but what’s your point exactly?”" src="https://cdn-images-1.medium.com/max/600/1*JwBJK_K8uFyWKHvwlSZkzQ.jpeg" /><figcaption>Image Source Google</figcaption></figure><p>In this part, let’s explore why we need Procs, Lambdas, and Blocks in the first place and how helpful using them with few examples and use cases.</p><p>Let’s get started…</p><h3>Why Blocks?</h3><blockquote><strong>Recap</strong>: A block is a piece of a code that is either enclosed within curly braces <strong><em>{}</em></strong> or a <strong><em>do..end</em></strong>. It is similar to a method but neither belongs to any object nor it has a name.</blockquote><p>To answer why blocks? and to understand the necessity of using them, we should answer one more question — <em>Can the </em><strong><em>identifier/reference</em></strong><em> of the ruby method be used as a </em><strong><em>first-class</em></strong><em> value or passed with no additional action?</em></p><p><strong>No</strong>. Ruby methods are not <a href="https://en.wikipedia.org/wiki/First-class_function">First-Class Functions</a> unlike in few other languages, say Javascript.</p><blockquote>The identifier of a regular “function” in Ruby (which is really a method) cannot be used as a value or passed. It must first be retrieved into a Method or Proc object to be used as first-class data. — <a href="https://en.wikipedia.org/wiki/First-class_function">wiki</a></blockquote><p>To be used as a first-class value, It must first be captured into a Method or Proc object first.</p><pre><strong># Retrieving method reference into Method object</strong></pre><pre>def <strong>some_method</strong><br>  puts &quot;Called by Reference&quot;<br>end</pre><pre>method_reference = <strong>method(</strong>:some_method<strong>)</strong><br># &lt;Method: main.some_method&gt;</pre><pre># Calling the method using its reference</pre><pre>def <strong>some_other_method</strong>(method_ref_argument)<br>  # Do something before<br>  method_ref_argument<strong>.call<br>  </strong># Do some other things<strong><br></strong>end</pre><pre><strong>some_other_method</strong>(method_reference)<br># returns &quot;Called by Reference&quot;</pre><p>On the other hand, Blocks can be created “<strong>on the go</strong>” and we need not worry about reference. Let’s try to achieve the same as above with blocks.</p><pre># Block - No method reference capturing bullsh*t</pre><pre>def some_other_method(<strong>&amp;block_argument</strong>)<br>  # Do something before<br>  block_argument<strong>.call<br>  </strong># Do some other things<strong><br></strong>end</pre><pre>some_other_method<strong> { </strong>puts &quot;I am Block! and you are?&quot;<strong> }</strong><br># returns &quot;I am Block! and you are?&quot;</pre><p>With this approach, we do not need to create a method each time we want some custom things to happen in different methods.</p><p>Well, can blocks be assigned/referenced at all? <strong>Yes</strong>, which we call as procs and lambdas — don’t worry about this now, we will discuss in later sections.</p><p><strong>P.S.</strong> If you are curious about the &amp; symbol prepended to the method argument, here is a beautifully written <a href="https://ablogaboutcode.com/2012/01/04/the-ampersand-operator-in-ruby">article</a> that explains it.</p><h4>Do you have a point?</h4><blockquote>One method can be made to work in different means by injecting some custom code within the method from outside.</blockquote><p>In other words, Using the block gives back control to the programmer.</p><p>Let’s take a simple use-case….</p><p>A Customer Support System for a service provider, to manage support tickets that are raised by customers. Let’s just focus on ticket status and ignore other features.</p><p>A Ticket has one among open, on_hold or closed status. We have an API endpoint to mark the respective status for the tickets.</p><p>Usually, in our controller, we implement as below</p><pre>class TicketsController &lt; ApplicationController<br>  .....<br>  <br>  def mark_open<br>    if @ticket.<em>update</em>(status: &quot;open&quot;)<br>      # request response logic<br>    else<br>      # error handler<br>    end<br>  end</pre><pre>def mark_on_hold<br>    if @ticket.<em>update</em>(status: &quot;on_hold&quot;)<br>      # request response logic<br>    else<br>      # error handler<br>    end<br>  end</pre><pre>def mark_closed<br>    if @ticket.<em>update</em>(status: &quot;closed&quot;)<br>      # request response logic<br>    else<br>      # error handler<br>    end<br>  end</pre><pre>......<br>end</pre><p>We can notice the repeated code for each method to handle the response and errors. The primary action of these methods is to update status let alone handle requests and responses.</p><p>By using blocks we can abstract the request-response and error handling to a new method keeping the actions clean and more readable.</p><pre>class TicketsController &lt; ApplicationController<br>  .....<br>  <br>  def mark_open<br>    status_manager <strong>do</strong><br>      @ticket.<em>update</em>(status: &quot;open&quot;)<br>    <strong>end</strong><br>  end</pre><pre>def mark_on_hold<br>    status_manager <strong>do</strong><br>      @ticket.<em>update</em>(status: &quot;on_hold&quot;)<br>    <strong>end</strong><br>  end</pre><pre>def mark_closed<br>    status_manager <strong>do</strong><br>      @ticket.<em>update</em>(status: &quot;closed&quot;)<br>    <strong>end</strong><br>  end</pre><pre>def <strong>status_manager</strong><br>    is_status_changed = <strong>yield</strong></pre><pre>if is_status_changed<br>      # request response logic<br>    else<br>      # error handler<br>    end<br>  end</pre><pre>......<br>end</pre><h4>Okay, so where can I use Blocks?</h4><p>The status_manager from our Ticketing app use case is one of many use cases where blocks can be helpful.</p><p>For instance, consider a few array methods Array#each, Array#map, Array#select, etc., — all these methods accept a block.</p><pre>[&quot;procs&quot;, &quot;lambdas&quot;, &quot;blocks&quot;].each <strong>do</strong> |concept|<br>  puts &quot;Ruby - #{concept}&quot;<br><strong>end</strong></pre><p>We can do the same with a for loop or a while loop, literally any iterator. But, that’s a lot of code — In other terms, it is imperative programming. You can learn more about imperative, declarative and other programming paradigms <a href="https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms">here</a>.</p><p>I suppose, by now we have our answer to “<em>Why Blocks?”.</em></p><p>There is one limitation with blocks though. We can’t assign a block to a variable. Let’s say we want to implement similar functionality in more than one method. We have to send the block to each of the methods individually — this leads us to the next section “<em>Why Lambdas?”.</em></p><h3>Why Lambdas?</h3><blockquote><strong><em>Recap: </em></strong>A Lambda is very similar to a block and is also called an anonymous function. But, unlike blocks<em> </em><strong>lambdas are objects</strong> and can be assigned to variables with a special syntax.</blockquote><p><em>Using Lambdas and Procs, we can store a block in a variable and reuse. </em>To be more specific, blocks are useless without a method call. Also, lambdas can be called repeatedly without having to rewrite them every time, unlike blocks.</p><p>Lambdas give more flexibility than methods.</p><pre>greeter = <strong>-&gt;</strong> (greeting, name) <strong>{</strong> greeting + &quot; &quot; + name <strong>}</strong></pre><pre>greeter.call(&quot;Dear&quot;, &quot;Ruby Developer&quot;)<br># returns &quot;Dear Ruby Developer&quot;</pre><p><em>In simpler terms, lambda is like any other method that takes a block with an exception being assignable to variables.</em></p><p>Let’s consider the Ticketing System again, this time will update our blocks to a single lambda.</p><pre>class TicketsController &lt; ApplicationController<br>  ......<strong><br>  <br>  </strong>def mark_open<br>    status_manager(&quot;open&quot;)<br>  end</pre><pre>def mark_on_hold<br>   status_manager(&quot;on_hold&quot;)<br>  end</pre><pre>def mark_closed<br>    status_manager(&quot;closed&quot;)<br>  end</pre><pre><strong>status_updater</strong> = <strong>-&gt;</strong> (ticket, status) <strong>do</strong><br>    ticket.update(status: status)<br>  <strong>end</strong></pre><pre>def status_manager(status)<br>    is_status_changed = <strong>status_updater</strong>.call(@ticket, status)<br>    <br>    .....<br>  end</pre><pre>......<br>end</pre><p>Let’s take another use case and see how lambdas can be helpful.</p><p>This time we assume a gem for API service and we have a method called callback that is triggered for either success or failure responses. We need this method to be customizable and allow the gem user to define its functionality.</p><pre># gem code</pre><pre>class SomeAPIServiceController<br>  .....<br> <br>  def callback(<strong>on_success: on_failure:</strong>)<br>    if success<br>      <strong>on_success.call(res)</strong><br>    else<br>      <strong>on_failure.call(err)</strong><br>    end<br>  end</pre><pre>.....<br>end</pre><p>We can use blocks, but we are limited to use only one block per method call. So, how can we pass multiple blocks to this callback method?</p><p>Wait for it, Wait for it, lambdas lambdas yessss, lambdas to the rescue.</p><pre>success_callback = -&gt; (response) { # Do something with response }<br>failure_callback = -&gt; (error) { # Do something with error }</pre><pre>callback(on_success: <strong>success_callback</strong>, on_failure: <strong>failure_callback</strong>)</pre><p>With that we are left with the final question in our Blocks, Lambdas and Procs Exploration — <em>Why Procs?</em></p><p>With no further delay, let’s unravel the procs.</p><h3>Why Procs?</h3><blockquote><strong>Recap</strong>: Procs, the shorthand for Procedure, is a very similar concept to lambdas. <em>Procs are instances of ruby Proc class</em>.</blockquote><p>Lambdas are a special case of Procs and are a proc object. There is no dedicated Lambda class. If you have understood the <em>why Lambdas?</em> section, we already have our answer to <em>why Procs?</em></p><p>Also, we can use Procs instead of lambdas in every possible use-case, but lambdas and procs have their differences which I explained in <a href="https://medium.com/@krrish96/understanding-procs-lambdas-and-blocks-in-ruby-part-1-all-whats-answered-db91f30aab54">Part1: All’s What?s Answered</a>.</p><blockquote>Procs are full-fledged Objects and have all the abilities that an object does, while blocks on the other hand does not.</blockquote><p>Since lambdas and procs are objects we can do all the crazy stuff that an object can do.</p><pre>proc_object = Proc.new { puts &quot;I am Proc!&quot; }<br>#&lt;Proc:0x00007fc1ccfdcb50@(irb):9&gt;</pre><pre>proc_object.call<br># &quot;I am Proc!&quot;</pre><p>Well, that concludes our journey.</p><h3>That’s too much man 🤓</h3><figure><img alt="Tired Puppy, lying on the floor" src="https://cdn-images-1.medium.com/max/500/1*1j1YUHu66WFf-D-GkL6SJw.png" /><figcaption>Tired Puppy (Source: Google)</figcaption></figure><p>Let’s do a quick summary and play with our cute little 🐶 buddy….</p><ul><li>A method can neither be passed as argument nor be returned from another method (methods in ruby are not first-class functions).</li><li>Blocks are useless without method calls and have to be rewritten every time.</li><li>Blocks give back control to the programmer.</li><li>Procs are full-fledged Objects.</li><li>Lambdas are a special case of procs.</li><li>Lambdas are more flexible than methods.</li><li>Using blocks, lambdas, and procs. One method can be made to work in different aspects by injecting some custom code within the method from outside.</li></ul><h4>References</h4><ul><li><a href="https://stackoverflow.com/questions/10141124/any-difference-between-first-class-function-and-high-order-function">Any difference between First Class Function and High Order Function</a></li><li><a href="https://mixandgo.com/learn/mastering-ruby-blocks-in-less-than-5-minutes">Mastering Ruby Blocks in Less Than 5 Minutes</a></li><li><a href="https://www.rubyguides.com/2016/02/ruby-procs-and-lambdas/">The Ultimate Guide to Blocks, Procs &amp; Lambdas</a></li><li>And a lot of bits and pieces from mother google.</li></ul><p>I am a beginner to ruby, so please let me know if I have missed or misunderstood something above. I look forward to your suggestions and feedback in the comments section below.</p><p>I hope this article helped you understand procs, lambdas and blocks better. If you like this article please don’t forget to leave some 👏.</p><p>Thank you for reading this post, This is <a href="https://www.linkedin.com/in/kskp1996">Sai Krishna Prasad</a>, a self-taught and passionate web developer. Signing off Bubye….. until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6e46944356f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Procs, Lambdas, and Blocks in Ruby.]]></title>
            <link>https://medium.com/@krrish96/understanding-procs-lambdas-and-blocks-in-ruby-part-1-all-whats-answered-db91f30aab54?source=rss-f6683703c844------2</link>
            <guid isPermaLink="false">https://medium.com/p/db91f30aab54</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sai Krishna Prasad]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 13:30:02 GMT</pubDate>
            <atom:updated>2020-02-24T12:50:22.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Ruby Procs, Lambdas and Blocks. 1. All What?s Answered" src="https://cdn-images-1.medium.com/max/1024/1*9hMJKIA6LEP1haH7gU0GaA.png" /><figcaption>Procs, Lambdas, and Blocks in Ruby</figcaption></figure><h4>Part 1: All What?s Answered.</h4><p>I recently started learning ruby as part of my journey to be a full stack developer. I am using <a href="https://rubymonk.com/">rubymonk.com</a> which is a really good source for an absolute beginner. After a few smooth moving lessons and problems, I landed on the Procs and Lambdas section. I had a hard time understanding procs, lambdas, and blocks.</p><p>After spending a good amount of time with them, I finally have some clarity on how procs and lambdas work. Now I want to share my knowledge so that others will have an easier time understanding them.</p><p>I would like to explain procs and lambdas with two W questions, What? and Why? Let’s start with a few what?’s.</p><h3>What are the Blocks?</h3><p>Before jumping into procs and lambdas, let’s get a clear picture of what blocks are.</p><p>A block is a piece of a code that is either enclosed within curly braces <strong>{}</strong> or a <strong>do..end</strong>. It is similar to a method but neither belongs to any object nor it has a name. Syntactically {} is used for one-liner blocks and do..end for multi-line blocks. Let’s take a look at the following snippet to see the difference.</p><pre>concepts = [&#39;blocks&#39;, &#39;lambdas&#39;, &#39;procs&#39;]</pre><pre># One liner <strong>{}</strong> blocks<br>concepts.each <strong>{ </strong>|concept| puts &quot;Ruby: #{concept}&quot; <strong>}</strong></pre><pre># Multi-line <strong>do..end</strong> blocks<br>mastered_concepts = [&#39;blocks&#39;, &#39;procs&#39;]</pre><pre>concepts.each <strong>do </strong>|concept|</pre><pre>if mastered_concepts.include?(concept)<br>    puts &quot;I already mastered #{concept}&quot;<br>  else<br>    puts &quot;Yet to learn this #{concept}&quot;<br>  end</pre><pre><strong>end</strong></pre><h4>The Implicit Block with its friendly keyword yield.</h4><p>Blocks are also called closures in other languages. Blocks can be passed to a method either implicitly or explicitly. Only one block can be passed to a method.</p><p><strong><em>Implicit blocks</em></strong> are nameless and not necessarily we list them in the method arguments.</p><pre><strong>def</strong> implicit_block_method<br>  <strong>yield</strong><br><strong>end</strong></pre><pre>implicit_block_method <strong>do<br>  </strong>puts &quot;I am an implicit block, also I am nameless!&quot;<br><strong>end</strong></pre><p>Implicit Blocks can be invoked using the keyword yield. They can accept arguments too, if necessary. In other terms, blocks are just an anonymous chunk of code that is passed to a method to perform something.</p><pre><strong>def</strong> my_skills<br>  <strong>yield</strong> &quot;procs&quot;<br>  <strong>yield</strong> &quot;blocks&quot;<br><strong>end</strong></pre><pre>my_skills { |skill| puts &quot;I am skilled in Ruby #{skill}&quot; }</pre><p>One thing to note here is that yield is just a keyword that invokes the block as many times it is used inside a method.</p><h4>The Explicit Block and its name everything syndrome.</h4><p><strong><em>Explicit blocks</em></strong> are named and should be included in the arguments list.</p><p>The block should be the last argument that a method accepts. Explicit Blocks can be invoked by using the .call method on the block name.</p><pre><strong>def</strong> explicit_block_method(*argument_list, <strong>&amp;block_name</strong>)<br>  <strong>block_name</strong>.call<br><strong>end</strong></pre><pre>explicit_block_method <strong>do</strong> <br>  puts &quot;I am an explicit block, My name is block_name&quot;<br><strong>end</strong></pre><p>An Example with multiple arguments.</p><pre><strong>def</strong> block_caller_method(normal_argument, <strong>&amp;block_as_argument</strong>)<br>  puts &quot;I am #{normal_argument} inside method&quot;<br>  <strong>block_as_argument.call</strong> &quot;argument for block&quot;<br><strong>end</strong></pre><pre>block_caller_method(&quot;Normal argument&quot;) <strong>do</strong> |argument_for_block|<br>  puts &quot;Inside block and received #{argument_for_block}&quot;<br><strong>end</strong></pre><h4>Does a block return?</h4><p><strong>Yes</strong>, Blocks can return, just like methods. let’s talk about this in code.</p><pre>[&#39;ruby&#39;, &#39;javascript&#39;, &#39;python&#39;, &#39;java&#39;].select do |language|<br>  language.length == 4<br>end</pre><pre># returns [&#39;ruby&#39;, &#39;java&#39;]</pre><p>Here we are performing <a href="https://apidock.com/ruby/Array/select">Array#select</a> and passing in a block to specify our condition. This will return a new array with languages that have 4 character long names.</p><h4>Safeguard your method with “block_given?”</h4><p>Huff!! That’s a lot. There is one last thing we should know about blocks.</p><p>What if no block is passed to a method but we are expecting one, Ruby throws an error <strong>LocalJumpError </strong>if yield is used and <strong>NoMethodError</strong> if the method call is called on the block<strong>.</strong></p><pre><strong>def</strong> expecting_block<br>  yield<br><strong>end</strong></pre><pre>expecting_block<br># <strong>LocalJumpError (no block given (yield))</strong></pre><pre><strong>def</strong> me_to_expecting_block (&amp;block_name)<br>  block_name.call<br><strong>end</strong></pre><pre>me_to_expecting_block<br># <strong>NoMethodError (undefined method `call&#39; for nil:NilClass)</strong></pre><p>To fix this we just need to check if the block is given or not, using <strong>block_given?</strong>.</p><pre><strong>def</strong> is_block_given</pre><pre>if <strong>block_given?<br>    </strong>yield &quot;Yes&quot;<br>  else<br>    puts &quot;I am hurt :-/, I thought you would give me a block!&quot;<br>  end</pre><pre><strong>end</strong></pre><pre>is_block_given { |status| puts &quot;#{status} it is.&quot; }<br># Yes it is.</pre><pre>is_block_given<br># I am hurt :-/, I thought you would give me a block!</pre><h3>What are Lambdas?</h3><p>Now that we have some knowledge on blocks let’s move on to lambdas. Understanding blocks makes understanding lambdas much easier.</p><p>Lambda is the eleventh letter in the Greek alphabets…. Whaaaat? Oh, Shoot!! We are not talking about this(λ) lambda. Let’s get to know the lambdas in ruby then.</p><blockquote>A Lambda is very similar to a block and is also called an anonymous function. But, unlike blocks<em> </em><strong>lambdas are objects</strong> and can be assigned to variables with a special syntax.</blockquote><p>We can create lambda by using the keyword lambda or the -&gt; stab operator. The lambdas created with -&gt; stab operator are also called a stabby lambda.</p><pre># <strong>lambda</strong> block<br>lambda = <strong>lambda</strong> { puts &quot;I am a block declared with lambda&quot; }</pre><pre># <strong>-&gt;</strong> block<br>stabby_lambda = <strong>-&gt;</strong> { puts &quot;Alternate syntax, stabby lambda&quot; }</pre><h4>The Proc class</h4><p>When we created a lambda you might have observed something weird.</p><pre>lambda = <strong>lambda</strong> { puts &quot;A new lambda has been created.&quot; }</pre><pre># <strong>&lt;Proc:0x00007ff3758d7b68@(irb):54 (lambda)&gt;</strong></pre><p>The lambda is created as a new instance of the class Proc . Yes, This is fine. Because lambda’s do not have a dedicated class they are part of the classProc. You can check this by calling the method class on the lambda.</p><pre>lambda = <strong>lambda</strong> { puts &quot;Proc is my class!&quot;}</pre><pre>lambda.class<br># returns Proc</pre><p>Proc is the short form for Procedure, We will talk more about procs in the next section. You can happily ignore it for now.</p><h4>Arguments in lambda</h4><p>Lambdas also accept arguments, But the syntax for this is dependent on whether you’ve declared the lambda with the lambda keyword or with the-&gt; operator.</p><pre>lambda = <strong>lambda</strong> { <strong>|arg|</strong> puts &quot;I am lambda #{arg}.&quot; }</pre><pre>stabby_lambda = <strong>-&gt;</strong> <strong>(arg)</strong> { puts &quot;I am also lambda #{arg}.&quot; }</pre><pre>lambda.call &quot;Argument&quot;<br># I am lambda Argument.</pre><pre>stabby_lambda.call &quot;Argument&quot;<br># I am also lambda Argument.</pre><p>Lambdas can also be called in multiple ways.</p><pre>lambda = <strong>lambda</strong> { |name| puts &quot;Hello #{name}!&quot; }</pre><pre>lambda.call &quot;Ruby&quot;<br>lambda.(&quot;Ruby&quot;)<br>lambda[&quot;Ruby&quot;]<br>lambda.=== &quot;Ruby&quot;</pre><pre># all of them prints the same, &quot;Hello Ruby!&quot;</pre><h4>Lambda in action</h4><p>Lambdas can be stored in a variable and can be passed to any method as an argument.</p><pre>double_it = <strong>-&gt;</strong> (num) { num * 2}</pre><pre>[1,2,3,4,5].map(<strong><em>&amp;</em>double_it</strong>)<br># returns [2,4,6,8,10]</pre><p>Did you notice the <strong>&amp;</strong>(ampersand) symbol appended to double_it?. That’s a short form for calling the methodto_proc on the variable we stored. Also, <strong>&amp; </strong>is the one responsible for converting a lambda / proc to block. Usually, <a href="https://apidock.com/ruby/Array/map">Array#map</a> expects a block, not a lambda / proc.</p><pre><strong>&amp;double_it</strong> is equivalent to <strong>double_it.to_proc.call</strong></pre><p>That’s all we need to know about lambdas for now. Let’s move on to procs.</p><h3>What are Procs?</h3><p>Proc, the shorthand for Procedure, is a very similar concept to lambdas. Lambdas are a subpart of Procs. As we have already seen, the class for lambda is a Proc. Like lambdas, <strong><em>Procs are objects of ruby Proc class</em></strong>. Though lambdas and procs are similar, they also have their differences. But we will get to that in a bit.</p><p>We can create a proc with a new instance of the Proc class Proc.new or with the keyword proc which is again the same as Proc.new and is just syntactical sugar. Let&#39;s create some procs…</p><pre># <strong>Proc.new</strong> block<br>proc = <strong>Proc.new</strong> { puts &quot;I am proc, New instance of Proc class.&quot; }</pre><pre># <strong>proc</strong> block<br>new_proc = <strong>proc</strong> { puts &quot;I am a proc with keyword!&quot; }</pre><p>Calling procs and passing them arguments is very similar to lambdas, so I am not going to spend a whole lot of time on it. We should say lambdas are similar to procs. Just call the method class on lambda and proc and it answers everything. Both returns Proc .</p><pre>lambda = -&gt; {}<br>proc = proc {}</pre><pre>lambda.class<br>proc.class</pre><pre># both returns <strong>Proc</strong></pre><p>Also to show that lambdas and procs are objects, call superclass method on the class Proc . It returns Object .</p><pre>Proc.superclass</pre><pre># returns <strong>Object</strong></pre><h4>Procs vs Lambdas</h4><p>There are a couple of important differences between <strong>procs</strong> and <strong>lambdas </strong>specifically<strong> </strong>Arguments Handling and Return statement behavior.</p><p><strong>Arguments Handling, </strong>We have a very strict officer here. Guess Who? Yeah, you guessed it right. It’s officer Lambda.</p><p>Lambdas throw an exception (ArgumentError) when an incorrect number of arguments are passed.</p><pre>lambda = <strong>-&gt;</strong> (<strong>arg1, arg2</strong>) { puts &quot;I am strict, #{arg1} and #{arg2}&quot; }<br>lambda.call(&quot;<strong>Tough</strong>&quot;)</pre><pre># <strong>ArgumentError (wrong number of arguments (given 1, expected 2))</strong></pre><p>While Procs aren’t worried about them at all. If an extra argument is passed procs will ignore it. If fewer than expected arguments are passed procs will replace all the missed ones with nil.</p><pre>proc = proc { |<strong>arg</strong>| puts &quot;I am too lazy to care about #{arg}&quot; }<br>proc.call</pre><pre># I am too lazy to care about</pre><p>Though procs don’t throw an exception for the number of arguments, other cases could raise exceptions. For example:</p><pre>addition = proc { |num1, num2| num1+num2 }</pre><pre># passing only 1 argument<br>addition.call(1)<br># <strong>TypeError (nil can&#39;t be coerced into Integer)</strong></pre><pre># passing no arguments<br>addition.call<br>#<strong> NoMethodError (undefined method `+&#39; for nil:NilClass)</strong></pre><p>Here, proc is not worried about arguments and replaces the missed one with nil. Programmatically nil can’t be added to Integer. So, we get a <strong>TypeError </strong>or<strong> NoMethodError </strong>as above.</p><p>Just to be on the safer side, always set default values to arguments. If default values cannot be set make sure to pass the required number of arguments or have error handling blocks.</p><pre>addition = proc { |num1=0, num2=0| num1+num2 }</pre><pre>addition.call<br># returns 0</pre><pre>addition.call(2)<br># returns 2</pre><p><strong>Return statement Behavior</strong>, lambdas, and procs behave in a very different manner when comes to return statements.</p><p>Lambdas will return from the executing block/lambda and the further execution will continue as usual.</p><pre><strong>def</strong> return_from_lambda<br>  lambda = lambda { <strong>return</strong> &quot;I will just return from lambda!&quot; }</pre><pre>  puts &quot;I will execute, before lambda return!&quot;<br>  puts &quot;#{lambda.call}&quot;<br>  puts &quot;I too will execute, after lambda return!&quot;<br><strong>end</strong></pre><pre>return_from_lambda</pre><pre># I will execute, before lambda return!<br># I will just return from lambda!<br># I too will execute, after lambda return!</pre><p>While procs will return from the currently executing context/method.</p><pre><strong>def</strong> proc_return_method<br>  proc = proc { <strong>return</strong> &quot;I will return the method!&quot; }</pre><pre>  puts &quot;I will execute, before proc return.&quot;<br>  <strong>proc.call</strong><br>  puts &quot;I will never execute, after proc return!&quot;<br><strong>end</strong></pre><pre>proc_return_method</pre><pre># prints &quot;I will execute, before proc return!&quot;<br># returns &quot;I will return the method!&quot;</pre><p>There is one thing that we must know while handling returns with proc. As I mentioned proc will return from the method. If we just create a proc and call it without any context ruby raises a <strong>LocalJumpError</strong> as there is nothing to Jump back after returning from the current context.</p><pre>error_proc = proc { return &quot;I will raise exception&quot; }<br>error_proc.call</pre><pre># <strong>LocalJumpError (unexpected return)</strong></pre><p>Aaannnddddd!!! We are done.</p><h3>In Nutshell</h3><p><strong>Blocks</strong></p><ul><li>Block is a piece of code enclosed between <strong>{}</strong> or <strong>do..end</strong>.</li><li>Block neither belongs to any object nor it has a name.</li><li>Blocks can return just like methods.</li></ul><p><strong>Lambdas</strong></p><ul><li>Lambdas are objects, unlike blocks. Also, lambdas have a name and can be assigned to a variable for later use.</li><li>Lambda can be created either with the <strong>lambda</strong> keyword or with the <strong>-&gt;</strong> stab operator.</li><li>Lambdas are strict in terms of arguments.</li><li>Lambdas are a part of the <strong>Proc</strong> class.</li><li>Lambda returns from current lambda/block.</li></ul><p><strong>Procs</strong></p><ul><li>Procs are also objects and have a name.</li><li>Proc can be created by <strong>Proc.new</strong> or with keyword <strong>proc</strong>.</li><li>Procs aren’t worried about the number of arguments passed.</li><li>Proc returns from a method/current context.</li><li>Blocks, Lambdas, and Procs are all Closures.</li></ul><p>Well well, well!!! We made it! Now we have answers to most whats on Procs, Lambdas, and Blocks.</p><p>In the <a href="https://medium.com/@krrish96/understanding-procs-lambdas-and-blocks-in-ruby-part-2-all-whys-explained-f6e46944356f">next part</a> of this article, I will talk about next W “why?” with a few examples demonstrating why we need procs and lambdas in the first place.</p><p><strong>Update:</strong> <a href="https://medium.com/@krrish96/understanding-procs-lambdas-and-blocks-in-ruby-part-2-all-whys-explained-f6e46944356f">Part 2: All Why?s Explained</a> is published.</p><p>I am a beginner to ruby, so please let me know if I have missed or misunderstood something above. I look forward to your suggestions and feedback in the comments section below.</p><p>I hope this article helped you understand procs, lambdas and blocks better. If you like this article please don’t forget to leave some 👏.</p><p>Thank you for reading this post, This is <a href="https://www.linkedin.com/in/kskp1996">Sai Krishna Prasad</a>, a self-taught and passionate web developer. Signing off Bubye….. until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db91f30aab54" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>