<?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[TEZZA SOFTWARE DEVELOPMENT - Medium]]></title>
        <description><![CDATA[Software Development Stories from Tezza Business Solutions. - Medium]]></description>
        <link>https://medium.com/tezza-software-development?source=rss----9ced1f2ac33e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>TEZZA SOFTWARE DEVELOPMENT - Medium</title>
            <link>https://medium.com/tezza-software-development?source=rss----9ced1f2ac33e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:20:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/tezza-software-development" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ruby Closures]]></title>
            <link>https://medium.com/tezza-software-development/ruby-closures-b2a1fc2a4929?source=rss----9ced1f2ac33e---4</link>
            <guid isPermaLink="false">https://medium.com/p/b2a1fc2a4929</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Thiru Njuguna]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 20:16:01 GMT</pubDate>
            <atom:updated>2018-07-03T20:16:01.111Z</atom:updated>
            <content:encoded><![CDATA[<p>Closures are, without a doubt are Ruby’s nagging.</p><p>Blocks, procs, lambdas, and methods which are available in Ruby are collectively called closures.</p><p>As useful as they can be, their slight differences at times, make you feel they are just different names for the same Ruby construct.</p><p>However, if you look closely, they have their differences, and it takes an eager eye to figure them out.</p><p>We are going to analyze Ruby closures, and you will learn:</p><ol><li>What blocks, procs, lambdas, and methods are</li><li>How they differ from each other</li><li>How you can use blocks, procs, lambdas, and methods in your code</li></ol><h3>Blocks</h3><p>The simplest kind of closure is a block.A block is a chunk of code that can be passed to an object/method and is executed under the context of that object.If you have worked with arrays, you have probably used an array’s each method that allows you to iterate through the array’s contents.</p><pre><em>arr = [1, 2, 3, 4, 5]<br> <br>arr.each do | element |<br> puts element <br>end</em></pre><p>And here is the output.</p><pre><em>1<br> 2<br> 3<br> 4<br> 5</em></pre><p>In this case, the code between do and end which is puts element is a block.Although it is a block with a single line of code, blocks can be as long as hundred lines of code depending on what you are trying to achieve using a block.Below is an example that uses an array’s each_index function.</p><pre><em>arr = [50,4,5,7]<br> <br>arr.each_index do | i |<br>  puts ‘The element at #{i} is #{arr[i]}’ puts ‘The square of #{arr[i]} is # {arr[i]**2}’ puts ‘The cube of #{arr[i]} is #{arr[i]**3}’</em></pre><pre><em>end</em></pre><p>The code above produces the output.</p><pre><em>The element at 0 is 1<br> The square of 1 is 1<br> The cube of 1 is 1<br> The element at 1 is 2<br> The square of 2 is 4<br> The cube of 2 is 8<br> The element at 2 is 3<br> The square of 3 is 9<br> The cube of 3 is 27<br> The element at 3 is 4<br> The square of 4 is 16<br> The cube of 4 is 64<br> The element at 4 is 5<br> The square of 5 is 25<br> The cube of 5 is 125</em></pre><p>Notice the variables element and index that are enclosed within the | operator to pass into the block in both of our examples.Depending on how the block is written, you can pass one or more variables into your blocks.</p><p>The delete_if method of the Hash class is an example. It deletes all elements from the hash for which the block evaluates to true.</p><pre><em>hash = {a: 1, b: 2, c: 3, d: :d, e: :e, f: :f}<br> <br> hash = hash.delete_if do | key, value|<br>   key == value<br> end</em></pre><p>In this case, the hash variable is reduced to {a: 1, b: 2, c: 3}.</p><p>There is some object function in Ruby that accepts blocks then executes them in the object context they are passed to.</p><p>I recommend you read the <a href="https://www.ruby-lang.org/en/documentation/">official Ruby documentation</a> when working with any object. It is the best source to learn an object’s specifics and will also help you come across methods that accept blocks as a parameter.</p><p>So, knowing how to pass blocks to the core object methods is all good, but in a way, it limits our possibilities if we do not know how to write our methods that accept blocks.</p><h3>Writing Methods That Accept Blocks</h3><p>From our discussion on blocks so far, you might think that you are about to embark on the most complicated parts of this tutorial. But this isn’t the case.</p><p>Before we move to write our block-accepting methods, let us write a pure Post class that we can use throughout this article.</p><pre><em>class Post<br> attr_accessor :title, :content, :author, :publish_date<br> def initialize(title, content, author, publish_date)<br>  @title = title<br>  @content = content<br>  @author = author<br>  @publish_date = publish_date<br> end<br>end</em></pre><p>We have created a post-class with the attributes title, content, author, and publish_date. Using the attr_accessor method, we have made all these four attributes readable and writable. The object constructor which is the initialize method accepts all four of them as a parameter and sets merely the matching variables.</p><p>The next thing to note is the yield keyword.</p><p><em>As simple as it may sound, writing your block-accepting functions is just using the yield keyword.</em></p><p>I will showcase this by writing a block_inspec method in our post class, which accepts a block and pass in the post object’s instance variable names and values to the given block.</p><pre><em>class Post<br> attr_accessor :title, :content, :author, :publish_date<br> def initialize(title, content, author, publish_date)<br>   @title = title<br>   @content = content<br>   @author = author<br>   @publish_date = publish_date<br> end<br> <br> def block_inspect<br>   self.instance_variables.each do |instance_variable|<br>     stringified_instance_variable_name =   instance_variable.to_s.sub(‘@’, ‘’)<br>     yield(stringified_instance_variable_name,     self.instance_variable_get(instance_variable)) <br>   end<br> end<br>end</em></pre><p>To better understand our block_inspect method, let us first talk about the instance_variables and instance_variable_get methods.</p><p>Both the instance_variables and instance_variable_get methods are part of the core Object class. Since all objects inherit from Object in Ruby, they are automatically available on our post-class.</p><p>The instance_variables function returns an array of symbolized instance variable names.</p><p>In case of the post class, it would return.</p><pre><em>[:@title, :@content, :@author, :@publish_date]</em></pre><p>The instance_variable_get method returns the value for each of these instance variables. All you have to do is pass in the instance variable name.</p><p>So, instance_variable_get(:@title) would return the post’s title and so on.</p><p>Inside our block_inspect method, we have called self.instance_variables returns array:-</p><pre>[:@title, :@content, :@author, :@publish_date]</pre><p>Our code resolves to:-</p><pre><em>[:@title, :@content, :@author, :@publish_date]</em></pre><p><a href="/service/mailto::@publish_date%5D.each">Each</a> of them we as we saw before, this all us to work with each of the element in this array.</p><p>Because we want our post attribute names to be readable, we convert them to strings then get rid off @ symbol. This line</p><pre><em>stringified_instance_variable_name =instance_variable.to_s.sub(‘@’, ‘’)</em></pre><p>does that, saving the resulting string to the variable stringified_instance_variable_name.</p><p>The next part yield(stringified_instance_variable_name, self.instance_variable_get(instance_variable))is pretty simple and interesting.</p><p>By using the yield keyword, we are merely telling the compiler to take the block passed to this function and pass it the post instance variable’s name and value which are stringified_instance_variable_name, and self.instance_variable_get(instance_variable) respectively. These variables correspond to the variables passed to the block enclosed within the | operator.</p><p>Since we have used each function, It’s done for the post’s instance variables.</p><pre><em>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br> post.block_inspect do |k, v|<br>  puts “#{k} = #{v}”<br> end</em></pre><p>The output will be.</p><pre><em>title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date</em></pre><p>Though it looks like our block_inspect function is done, there is one more task we can add to it to make cleaner.</p><p>We outline the problem if we leave our block_inspect function as it is.</p><pre><em>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br>post.block_inspect</em></pre><p>If you run the above code, you’ll be greeted with the no block gave (yield) (LocalJumpError) error.</p><p>This means our block_inspect method assumes a block is passed when it is invoked.</p><p>However, imagine if you are creating a REST API. The LocalJumpError, whenever encountered, would break your whole app for no reason.</p><p>To remedy that, we need to tell our block_inspect function to invoke the block if it is given using the block_given? Function.</p><p>Below is the re-written block_inspect function.</p><pre><em>def block_inspect<br> self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   if block_given?<br>     yield(stringified_instance_variable_name, self.instance_variable_get(instance_variable))<br>   end<br> end<br>end</em></pre><p>Or a neater way to do this would be.</p><pre><em>def block_inspect<br> self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   yield(stringified_instance_variable_name, self.instance_variable_get(instance_variable)) if block_given? <br> end<br>end</em></pre><p>Now, try the block_inspect method again without passing any block. The LocalJumpError is no longer encountered, and everything functions as it should.</p><p>Apart from yield, we can use a block’s call method to write block-accepting functions, but by using it, we have to explicitly declare in our method definition that a block will be passed to it.</p><p>Let’s edit the block_inspect method once again to understand how that is done.</p><pre><em>def block_inspect(&amp;block)<br> self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   block.call(stringified_instance_variable_name, self.instance_variable_get(instance_variable)) if block_given? <br> end<br>end</em></pre><p>Starting with the method signature, we have explicitly added a block to the parameters list. The only change apart from that is invoking the block using block. Call and pass the variable instance of names and values so that they are available in the block.</p><p>Note that we have included &amp; before block when specifying the function parameters. It means that the blocks need not be passed by value, but by reference.</p><h3>Procs</h3><p>The easiest way to understand procs (short for procedures) is when you save your blocks to a variable, it is called a proc.</p><p>In other words, a block is a proc, only that it has been declared inline and not saved to a variable.</p><p>Here is a proof of concept.</p><p>Let us write a very simple function that accepts a block as a parameter. We will only be echoing the class of the passed block inside the function.</p><pre><em>def show_class(&amp;block_object)<br> puts “The block class is #{block_object.class}” if block_given?<br> yield if block_given?<br>end<br>show_class do<br> puts “Hi! from inside the block.”<br>end</em></pre><p>The output is:-</p><pre>The block class is Proc<br>Hi! from inside the block</pre><p>Let us add another function to post class for inspection with proc.</p><pre><em>def proc_inspect(block)<br>  self.instance_variables.each do |instance_variable|<br>    stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>    block.call(stringified_instance_variable_name, self.instance_variable_get(instance_variable))<br>  end<br>end</em></pre><p>The proc_inspect function looks like the block_inspect function, the only changes done is getting rid off &amp; before the method parameter and block_given? Conditional.</p><p>The proc_inspect function works like any other method and will be able to know the number of parameters required.</p><p>In case a proc is not passed to the method, there will be a wrong number of arguments error instead of a LocalJumpError.</p><p>Here is the proc_inspect method in action.</p><pre><em>proc_inspect = Proc.new do |attribute, value|<br> puts “#{attribute} = #{value}”<br>end </em><br><em>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br>post.proc_inspect(proc_inspect)</em></pre><p>The above code output is as same as before.</p><p>As mentioned earlier, procs are blocks that can be saved to a variable, as clearly illustrated in the first line of code.</p><p>The next two lines create a post object and pass it the proc object using the proc_inspect function.</p><p><em>Procs make code re-usable.</em>Imagine if you wrote a 1000-line block that goes through an object, detailing its specifics like attribute names, values, and the memory each of them consumes.</p><p>In such a case, writing a 100-line block in-line everywhere it needs to be used sounds very untidy and impractical.</p><p>For such scenarios and similar, you can create a proc and merely call it when it’s needed.</p><h3>Lambdas</h3><p>Lambdas look the same as procs. Let us see their practical implementation.</p><p>Add another function lambda_inspect in the post class.</p><pre><em>def lambda_inspect(lambda)<br>  self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   lambda.call(stringified_instance_variable_name, self.instance_variable_get(instance_variable))<br>  end<br>end</em></pre><p>It is like the proc_inspect function and calling it will not outline any differences except for a few.</p><pre><em>lambda_inspect = lambda do |k, v|<br> puts “#{k} = #{v}”<br>end<br>post.lambda_inspect(lambda_inspect)</em></pre><p>So what are the differences?</p><p>Well,</p><p>The first one is a proc doesn’t report an error if the number of parameters passed doesn’t match the number of parameters it should accept whereas a lambda matches.</p><p>See below.</p><pre><em>proc_inspect = Proc.new do |k,v, answer_to_method|<br> puts “#{k} = #{v}”<br> puts ‘Answer to method is #{answer_to_method.class}’end<br> <br> post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br> post.proc_inspect(proc_inspect)</em></pre><p>Output is:-</p><pre><em>title = Title<br> Answer to method is NilClass<br> content = Content<br> Answer to method is NilClass<br> author = Author<br> Answer to method is NilClass<br> publish_date = Publish_Date<br> Answer to method is NilClass</em></pre><p>The class of answer_to_method is printed NilClass for all the iterations. We could have printed the variable answer_to_life_and_universe using puts answer_to_life_and_universe, but since it is NIL, nothing is printed out.</p><p>Now, let us do the same thing using a lambda.</p><pre><em>lambda_inspect = lambda do |attribute, value, answer_to_life_and_universe|<br>   puts “#{attribute} = #{value}”<br>   puts “Answer to life and universe is #{answer_to_life_and_universe.class}”<br> end<br> <br> post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br> post.lambda_inspect(lambda_inspect)</em></pre><p>You will be greeted with the wrong number of arguments (given 2, expected 3) error and the compiler will be all over you like an angry girlfriend.</p><p>The second difference has to do with the return keyword.</p><p>When you use return inside a proc (which is inside a function), it behaves as though using return inside the function, halting further execution and exiting the function with the returned value.</p><p>Whereas in case of lambdas, only the value is returned and the function resumes execution as<strong> </strong>usual.</p><pre><em>def proc_return<br>   Proc.new do <br>    return &#39;Inside proc&#39;  end.call<br>   return &#39;Inside proc_return!!&quot;&#39;end<br> <br>def lambda_return<br>  lambda do<br>    return &#39;Inside lambda_inspect!!&quot;&#39;  end.call<br>   return &#39;Inside lambda_return!!&quot;  &#39;end<br> </em></pre><pre><em> <br>puts proc_return<br>puts lambda_return</em></pre><p>The output is:-</p><pre><em>Inside proc <br>Inside lambda_return</em></pre><h3>Methods</h3><p><em>Functions and object methods can be called methods.</em></p><p>There is nothing much to discuss regarding the specifics of methods.</p><p>However, concerning closures, it is worth mentioning that (tongue twister alert!) the method makes methods usable in place of blocks, procs, and lambdas.</p><pre><em>def print_object_property(attribute, value)<br>  puts “#{attribute} = #{value}”<br>end<br> <br>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br>post.block_inspect(&amp;(method(:print_object_property)))<br>puts ‘ ‘post.proc_inspect(method(:print_object_property))<br>puts ‘ ‘post.lambda_inspect(method(:print_object_property))</em></pre><p>The output shows our function is used in place of a block, proc, and lambda flawlessly.</p><pre><em>title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date<br> <br> title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date<br> <br> title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date</em></pre><h3>Ruby Closures</h3><p>Closures are, without a doubt are Ruby’s nagging.</p><p>Blocks, procs, lambdas, and methods which are available in Ruby are collectively called closures.</p><p>As useful as they can be, their slight differences at times, make you feel they are just different names for the same Ruby construct.</p><p>However, if you look closely, they have their differences, and it takes an eager eye to figure them out.</p><p>We are going to analyze Ruby closures, and you will learn:</p><ol><li>What blocks, procs, lambdas, and methods are</li><li>How they differ from each other</li><li>How you can use blocks, procs, lambdas, and methods in your code</li></ol><h3>Blocks</h3><p>The simplest kind of closure is a block.A block is a chunk of code that can be passed to an object/method and is executed under the context of that object.If you have worked with arrays, you have probably used an array’s each method that allows you to iterate through the array’s contents.</p><pre><em>arr = [1, 2, 3, 4, 5]<br> <br>arr.each do | element |<br> puts element <br>end</em></pre><p>And here is the output.</p><pre><em>1<br> 2<br> 3<br> 4<br> 5</em></pre><p>In this case, the code between do and end which is puts element is a block.Although it is a block with a single line of code, blocks can be as long as hundred lines of code depending on what you are trying to achieve using a block.Below is an example that uses an array’s each_index function.</p><pre><em>arr = [50,4,5,7]<br> <br>arr.each_index do | i |<br>  puts ‘The element at #{i} is #{arr[i]}’ puts ‘The square of #{arr[i]} is # {arr[i]**2}’ puts ‘The cube of #{arr[i]} is #{arr[i]**3}’</em></pre><pre><em>end</em></pre><p>The code above produces the output.</p><pre><em>The element at 0 is 1<br> The square of 1 is 1<br> The cube of 1 is 1<br> The element at 1 is 2<br> The square of 2 is 4<br> The cube of 2 is 8<br> The element at 2 is 3<br> The square of 3 is 9<br> The cube of 3 is 27<br> The element at 3 is 4<br> The square of 4 is 16<br> The cube of 4 is 64<br> The element at 4 is 5<br> The square of 5 is 25<br> The cube of 5 is 125</em></pre><p>Notice the variables element and index that are enclosed within the | operator to pass into the block in both of our examples.Depending on how the block is written, you can pass one or more variables into your blocks.</p><p>The delete_if method of the Hash class is an example. It deletes all elements from the hash for which the block evaluates to true.</p><pre><em>hash = {a: 1, b: 2, c: 3, d: :d, e: :e, f: :f}<br> <br> hash = hash.delete_if do | key, value|<br>   key == value<br> end</em></pre><p>In this case, the hash variable is reduced to {a: 1, b: 2, c: 3}.</p><p>There is some object function in Ruby that accepts blocks then executes them in the object context they are passed to.</p><p>I recommend you read the <a href="https://www.ruby-lang.org/en/documentation/">official Ruby documentation</a> when working with any object. It is the best source to learn an object’s specifics and will also help you come across methods that accept blocks as a parameter.</p><p>So, knowing how to pass blocks to the core object methods is all good, but in a way, it limits our possibilities if we do not know how to write our methods that accept blocks.</p><h3>Writing Methods That Accept Blocks</h3><p>From our discussion on blocks so far, you might think that you are about to embark on the most complicated parts of this tutorial. But this isn’t the case.</p><p>Before we move to write our block-accepting methods, let us write a pure Post class that we can use throughout this article.</p><pre><em>class Post<br> attr_accessor :title, :content, :author, :publish_date<br> def initialize(title, content, author, publish_date)<br>  @title = title<br>  @content = content<br>  @author = author<br>  @publish_date = publish_date<br> end<br>end</em></pre><p>We have created a post-class with the attributes title, content, author, and publish_date. Using the attr_accessor method, we have made all these four attributes readable and writable. The object constructor which is the initialize method accepts all four of them as a parameter and sets merely the matching variables.</p><p>The next thing to note is the yield keyword.</p><p><em>As simple as it may sound, writing your block-accepting functions is just using the yield keyword.</em></p><p>I will showcase this by writing a block_inspec method in our post class, which accepts a block and pass in the post object’s instance variable names and values to the given block.</p><pre><em>class Post<br> attr_accessor :title, :content, :author, :publish_date<br> def initialize(title, content, author, publish_date)<br>   @title = title<br>   @content = content<br>   @author = author<br>   @publish_date = publish_date<br> end<br> <br> def block_inspect<br>   self.instance_variables.each do |instance_variable|<br>     stringified_instance_variable_name =   instance_variable.to_s.sub(‘@’, ‘’)<br>     yield(stringified_instance_variable_name,     self.instance_variable_get(instance_variable)) <br>   end<br> end<br>end</em></pre><p>To better understand our block_inspect method, let us first talk about the instance_variables and instance_variable_get methods.</p><p>Both the instance_variables and instance_variable_get methods are part of the core Object class. Since all objects inherit from Object in Ruby, they are automatically available on our post-class.</p><p>The instance_variables function returns an array of symbolized instance variable names.</p><p>In case of the post class, it would return.</p><pre><em>[:@title, :@content, :@author, :@publish_date]</em></pre><p>The instance_variable_get method returns the value for each of these instance variables. All you have to do is pass in the instance variable name.</p><p>So, instance_variable_get(:@title) would return the post’s title and so on.</p><p>Inside our block_inspect method, we have called self.instance_variables returns array:-</p><pre>[:@title, :@content, :@author, :@publish_date]</pre><p>Our code resolves to:-</p><pre><em>[:@title, :@content, :@author, :@publish_date]</em></pre><p><a href="/service/mailto::@publish_date%5D.each">Each</a> of them we as we saw before, this all us to work with each of the element in this array.</p><p>Because we want our post attribute names to be readable, we convert them to strings then get rid off @ symbol. This line</p><pre><em>stringified_instance_variable_name =instance_variable.to_s.sub(‘@’, ‘’)</em></pre><p>does that, saving the resulting string to the variable stringified_instance_variable_name.</p><p>The next part yield(stringified_instance_variable_name, self.instance_variable_get(instance_variable))is pretty simple and interesting.</p><p>By using the yield keyword, we are merely telling the compiler to take the block passed to this function and pass it the post instance variable’s name and value which are stringified_instance_variable_name, and self.instance_variable_get(instance_variable) respectively. These variables correspond to the variables passed to the block enclosed within the | operator.</p><p>Since we have used each function, It’s done for the post’s instance variables.</p><pre><em>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br> post.block_inspect do |k, v|<br>  puts “#{k} = #{v}”<br> end</em></pre><p>The output will be.</p><pre><em>title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date</em></pre><p>Though it looks like our block_inspect function is done, there is one more task we can add to it to make cleaner.</p><p>We outline the problem if we leave our block_inspect function as it is.</p><pre><em>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br>post.block_inspect</em></pre><p>If you run the above code, you’ll be greeted with the no block gave (yield) (LocalJumpError) error.</p><p>This means our block_inspect method assumes a block is passed when it is invoked.</p><p>However, imagine if you are creating a REST API. The LocalJumpError, whenever encountered, would break your whole app for no reason.</p><p>To remedy that, we need to tell our block_inspect function to invoke the block if it is given using the block_given? Function.</p><p>Below is the re-written block_inspect function.</p><pre><em>def block_inspect<br> self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   if block_given?<br>     yield(stringified_instance_variable_name, self.instance_variable_get(instance_variable))<br>   end<br> end<br>end</em></pre><p>Or a neater way to do this would be.</p><pre><em>def block_inspect<br> self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   yield(stringified_instance_variable_name, self.instance_variable_get(instance_variable)) if block_given? <br> end<br>end</em></pre><p>Now, try the block_inspect method again without passing any block. The LocalJumpError is no longer encountered, and everything functions as it should.</p><p>Apart from yield, we can use a block’s call method to write block-accepting functions, but by using it, we have to explicitly declare in our method definition that a block will be passed to it.</p><p>Let’s edit the block_inspect method once again to understand how that is done.</p><pre><em>def block_inspect(&amp;block)<br> self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   block.call(stringified_instance_variable_name, self.instance_variable_get(instance_variable)) if block_given? <br> end<br>end</em></pre><p>Starting with the method signature, we have explicitly added a block to the parameters list. The only change apart from that is invoking the block using block. Call and pass the variable instance of names and values so that they are available in the block.</p><p>Note that we have included &amp; before block when specifying the function parameters. It means that the blocks need not be passed by value, but by reference.</p><h3>Procs</h3><p>The easiest way to understand procs (short for procedures) is when you save your blocks to a variable, it is called a proc.</p><p>In other words, a block is a proc, only that it has been declared inline and not saved to a variable.</p><p>Here is a proof of concept.</p><p>Let us write a very simple function that accepts a block as a parameter. We will only be echoing the class of the passed block inside the function.</p><pre><em>def show_class(&amp;block_object)<br> puts “The block class is #{block_object.class}” if block_given?<br> yield if block_given?<br>end<br>show_class do<br> puts “Hi! from inside the block.”<br>end</em></pre><p>The output is:-</p><pre>The block class is Proc<br>Hi! from inside the block</pre><p>Let us add another function to post class for inspection with proc.</p><pre><em>def proc_inspect(block)<br>  self.instance_variables.each do |instance_variable|<br>    stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>    block.call(stringified_instance_variable_name, self.instance_variable_get(instance_variable))<br>  end<br>end</em></pre><p>The proc_inspect function looks like the block_inspect function, the only changes done is getting rid off &amp; before the method parameter and block_given? Conditional.</p><p>The proc_inspect function works like any other method and will be able to know the number of parameters required.</p><p>In case a proc is not passed to the method, there will be a wrong number of arguments error instead of a LocalJumpError.</p><p>Here is the proc_inspect method in action.</p><pre><em>proc_inspect = Proc.new do |attribute, value|<br> puts “#{attribute} = #{value}”<br>end </em><br><em>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br>post.proc_inspect(proc_inspect)</em></pre><p>The above code output is as same as before.</p><p>As mentioned earlier, procs are blocks that can be saved to a variable, as clearly illustrated in the first line of code.</p><p>The next two lines create a post object and pass it the proc object using the proc_inspect function.</p><p><em>Procs make code re-usable.</em>Imagine if you wrote a 1000-line block that goes through an object, detailing its specifics like attribute names, values, and the memory each of them consumes.</p><p>In such a case, writing a 100-line block in-line everywhere it needs to be used sounds very untidy and impractical.</p><p>For such scenarios and similar, you can create a proc and merely call it when it’s needed.</p><h3>Lambdas</h3><p>Lambdas look the same as procs. Let us see their practical implementation.</p><p>Add another function lambda_inspect in the post class.</p><pre><em>def lambda_inspect(lambda)<br>  self.instance_variables.each do |instance_variable|<br>   stringified_instance_variable_name = instance_variable.to_s.sub(‘@’, ‘’)<br>   lambda.call(stringified_instance_variable_name, self.instance_variable_get(instance_variable))<br>  end<br>end</em></pre><p>It is like the proc_inspect function and calling it will not outline any differences except for a few.</p><pre><em>lambda_inspect = lambda do |k, v|<br> puts “#{k} = #{v}”<br>end<br>post.lambda_inspect(lambda_inspect)</em></pre><p>So what are the differences?</p><p>Well,</p><p>The first one is a proc doesn’t report an error if the number of parameters passed doesn’t match the number of parameters it should accept whereas a lambda matches.</p><p>See below.</p><pre><em>proc_inspect = Proc.new do |k,v, answer_to_method|<br> puts “#{k} = #{v}”<br> puts ‘Answer to method is #{answer_to_method.class}’end<br> <br> post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br> post.proc_inspect(proc_inspect)</em></pre><p>Output is:-</p><pre><em>title = Title<br> Answer to method is NilClass<br> content = Content<br> Answer to method is NilClass<br> author = Author<br> Answer to method is NilClass<br> publish_date = Publish_Date<br> Answer to method is NilClass</em></pre><p>The class of answer_to_method is printed NilClass for all the iterations. We could have printed the variable answer_to_life_and_universe using puts answer_to_life_and_universe, but since it is NIL, nothing is printed out.</p><p>Now, let us do the same thing using a lambda.</p><pre><em>lambda_inspect = lambda do |attribute, value, answer_to_life_and_universe|<br>   puts “#{attribute} = #{value}”<br>   puts “Answer to life and universe is #{answer_to_life_and_universe.class}”<br> end<br> <br> post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br> <br> post.lambda_inspect(lambda_inspect)</em></pre><p>You will be greeted with the wrong number of arguments (given 2, expected 3) error and the compiler will be all over you like an angry girlfriend.</p><p>The second difference has to do with the return keyword.</p><p>When you use return inside a proc (which is inside a function), it behaves as though using return inside the function, halting further execution and exiting the function with the returned value.</p><p>Whereas in case of lambdas, only the value is returned and the function resumes execution as<strong> </strong>usual.</p><pre><em>def proc_return<br>   Proc.new do <br>    return &#39;Inside proc&#39;  end.call<br>   return &#39;Inside proc_return!!&quot;&#39;end<br> <br>def lambda_return<br>  lambda do<br>    return &#39;Inside lambda_inspect!!&quot;&#39;  end.call<br>   return &#39;Inside lambda_return!!&quot;  &#39;end<br> </em></pre><pre><em> <br>puts proc_return<br>puts lambda_return</em></pre><p>The output is:-</p><pre><em>Inside proc <br>Inside lambda_return</em></pre><h3>Methods</h3><p><em>Functions and object methods can be called methods.</em></p><p>There is nothing much to discuss regarding the specifics of methods.</p><p>However, concerning closures, it is worth mentioning that (tongue twister alert!) the method makes methods usable in place of blocks, procs, and lambdas.</p><pre><em>def print_object_property(attribute, value)<br>  puts “#{attribute} = #{value}”<br>end<br> <br>post = Post.new(“Title”, “Content”, “Author”, “Publish_Date”)<br>post.block_inspect(&amp;(method(:print_object_property)))<br>puts ‘ ‘post.proc_inspect(method(:print_object_property))<br>puts ‘ ‘post.lambda_inspect(method(:print_object_property))</em></pre><p>The output shows our function is used in place of a block, proc, and lambda flawlessly.</p><pre><em>title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date<br> <br> title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date<br> <br> title = Title<br> content = Content<br> author = Author<br> publish_date = Publish_Date</em></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2a1fc2a4929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tezza-software-development/ruby-closures-b2a1fc2a4929">Ruby Closures</a> was originally published in <a href="https://medium.com/tezza-software-development">TEZZA SOFTWARE DEVELOPMENT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns in Ruby.]]></title>
            <link>https://medium.com/tezza-software-development/design-patterns-in-ruby-11eac07ef421?source=rss----9ced1f2ac33e---4</link>
            <guid isPermaLink="false">https://medium.com/p/11eac07ef421</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[KAMAL OGUDAH]]></dc:creator>
            <pubDate>Tue, 15 May 2018 17:51:37 GMT</pubDate>
            <atom:updated>2018-05-15T17:46:27.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*nwakpRp_GabhICWPNw5VDQ.png" /><figcaption><a href="http://www.deepakkamboj.com/wp-content/uploads/2015/11/designpatterns-720x340.png"><strong>Credits</strong></a></figcaption></figure><p>So you have grasped all the basics of the programming language of your choice, this may be Java, C++ , Python, Javascript, or Ruby (like it was in my case). This is the time you feel capable of doing anything with the knowledge you now have. Out you go, always championing and evangelising about your language, giving presentations in user groups.</p><p>Then in your first job as a developer, you get to work with the Journeymen and women, and masters of the craft. Making your first commit on the project codebase, the code review comes in, among the comments you get, “use composition over inheritance”, “In this part you could have used a decorator” among other foreign terms that the makes you feel like a novice all over again. This is especially true if you are self taught, or your mentors did not see the need to mention design patterns or SOLID principles. Well, there is more stuff to learn beyond the basics of programming.</p><blockquote>To understand is to perceive patterns ~ Isaiah Berlin</blockquote><p>Building software that works is an exciting undertaking for any new apprentice. However, beyond the toy projects and breakable toys that you were used to developing, there exist the real world which not only requires a working software, but that which has been well structured in a manner that it demonstrates the highest standards of craftmanship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*MhbLALhWDNFv4TamP7ff6w.png" /><figcaption>Not this Patterns <a href="https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/633cfb87-6bf3-40f8-8749-76e8d8178637/responsive-graph.png"><strong>Credit</strong></a></figcaption></figure><p>This post is the beginning of a series that will cover Design Patterns as can be applied to the Ruby Language. Information acquired in the series can be applied to any other language within the OOP family. As an apprentice, adding design patterns in your body of knowledge is good, but take caution as too much of something can be dangerous. This calls for making use of design patterns sparingly, when crafting software it is best to strive for simplicity, as too much design patterns may result in over engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*dkTeUYqMmmOhEi5yhYIVHg.jpeg" /><figcaption>Ruby on Rails <a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSq5GWh9lNe14zGOojAEMBFgDeJXU1EqtVV4WutPoSkb6P4Qsu2"><strong>Credit</strong></a></figcaption></figure><p>Knowing design patterns at heart will make you a better developer, besides during interviews you can wade into the deep end of interview questions like a boss. Since, design patterns go hand in hand with SOLID Design principles, that is what will introduce the series. I am Looking forward to your audience and readership.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11eac07ef421" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tezza-software-development/design-patterns-in-ruby-11eac07ef421">Design Patterns in Ruby.</a> was originally published in <a href="https://medium.com/tezza-software-development">TEZZA SOFTWARE DEVELOPMENT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>