<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Ruby - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Ruby - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:30:32 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/ruby/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Brief Introduction to Ruby ]]>
                </title>
                <description>
                    <![CDATA[ Ruby is a programming language designed with developer happiness in mind. Its elegant and intuitive syntax makes coding not only productive but also enjoyable. Ruby stands out with its powerful metaprogramming capabilities, allowing developers to tre... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-brief-introduction-to-ruby/</link>
                <guid isPermaLink="false">68a5f79379e37ec1bf4b9b72</guid>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby on Rails ]]>
                    </category>
                
                    <category>
                        <![CDATA[ sinatra ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Wed, 20 Aug 2025 16:28:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755707266513/270f71d0-0e56-46f6-bba1-7b369dd97f1d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Ruby is a programming language designed with developer happiness in mind. Its elegant and intuitive syntax makes coding not only productive but also enjoyable. Ruby stands out with its powerful metaprogramming capabilities, allowing developers to treat code as data and manipulate it at runtime.</p>
<p>While many modern languages offer similar features, Ruby consistently delivers a seamless and joyful experience. Whether you're building a startup MVP, a scalable enterprise application, or a lightweight API, Ruby has you covered with frameworks like <a target="_blank" href="https://rubyonrails.org/">Rails</a> and <a target="_blank" href="https://sinatrarb.com/">Sinatra</a>.</p>
<p>Despite the growing popularity of JavaScript and Python, Ruby remains a valuable language to learn, not just for its utility, but for how it teaches you to write clean, expressive, and maintainable code.</p>
<p>If you've heard of Ruby but never used it, this tutorial is the perfect starting point. Designed to be completed in an afternoon, it offers a glimpse into what makes Ruby so beloved by developers. While it doesn't cover every aspect of the language, Ruby's intuitive nature ensures you'll be well prepared to dive right into frameworks like Sinatra or Rails after completing it.</p>
<h2 id="heading-code-playbacks"><strong>Code Playbacks</strong></h2>
<p>Code playbacks are a unique way to learn about programming. They are guided walkthroughs of code, allowing you to see not just the code itself but also the thought process behind it. This approach helps you understand not only what the code does, but <em>why</em> it was written that way. Here is a short video to show how to move through a code playback:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uYbHqCNjVDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>By registering on <a target="_blank" href="https://playbackpress.com/books">Playback Press</a>, you’ll gain access to an AI assistant that can answer your questions about the code. This makes learning even more interactive and personalized. Watch this video to see how to work with it:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/WAPql5KZFR4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-a-brief-introduction-to-ruby"><strong>A Brief Introduction to Ruby</strong></h2>
<p>You can find my entire collection of Ruby code playbacks in my free book, <a target="_blank" href="https://playbackpress.com/books/rubybook/">"A Brief Introduction to Ruby"</a>. Here's a quick look at what you'll learn:</p>
<h3 id="heading-highlights"><strong>Highlights</strong></h3>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/1"><strong>1.1 Hello Ruby!!!</strong></a>: Write your first Ruby program and learn how to run it from the terminal.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/2"><strong>1.2 Variables and Types</strong></a>: Explore Ruby's variables, constants, and string interpolation.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/3"><strong>1.3 Selection and Looping</strong></a>: Master control flow with if statements, loops, and ranges.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/4"><strong>1.4 Arrays</strong></a>: Work with arrays, one of Ruby's most versatile data structures.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/5"><strong>1.5 Hashes</strong></a>: Learn about hashes, Ruby's equivalent of dictionaries or associative arrays.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/6"><strong>1.6 Methods</strong></a>: Write reusable code with methods, parameters, and return values.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/7"><strong>1.7 Closures</strong></a>: Discover how to pass code into methods and execute it with <code>yield</code>.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/8"><strong>1.8 Iterators</strong></a>: Simplify data iteration with Ruby's powerful higher-order methods.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/9"><strong>1.9 Classes in Ruby</strong></a>: Build objects with classes, instance variables, and inheritance.</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/10"><strong>1.10 Interacting Classes</strong></a>: Create cooperating classes and explore Ruby's "duck typing."</p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook/chapter/1/11"><strong>1.11 Unit Testing in Ruby</strong></a>: Write tests to ensure your code works as expected.</p>
</li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Ready to start your Ruby journey? Begin with the first playback and experience how fun and intuitive Ruby can be. Whether you're a complete beginner or an experienced developer, there's something here for everyone!</p>
<p>I’d love to hear your thoughts! Feel free to share your comments, questions, or feedback via email: <a target="_blank" href="https://file+.vscode-resource.vscode-cdn.net/Users/mmahoney/Dropbox/animCPPBook2021/devToBlogPosts/ruby/mark@playbackpress.com">mark@playbackpress.com</a>. Your input helps me improve and create even better content.</p>
<p>If you’ve found this tutorial helpful, consider supporting my work through <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. Your contributions help cover hosting costs and keep Playback Press free for everyone. Thank you for helping me continue creating educational resources for the developer community!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Don't Use the Mac System Ruby – Use This Instead ]]>
                </title>
                <description>
                    <![CDATA[ Someone may have once told you, "Don't use the system Ruby." It's good advice, but why? Let's find out. Which Ruby do you have? MacOS comes with a "system Ruby" pre-installed. Use the which command to see where Ruby is installed: $ which ruby /usr/bi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/do-not-use-mac-system-ruby-do-this-instead/</link>
                <guid isPermaLink="false">66ba15fb228e16bed602a8bc</guid>
                
                    <category>
                        <![CDATA[ best practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mac ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Daniel Kehoe ]]>
                </dc:creator>
                <pubDate>Wed, 10 Feb 2021 17:27:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/02/photo-1522776851755-3914469f0ca2.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Someone may have once told you, "Don't use the system Ruby." It's good advice, but why? Let's find out.</p>
<h2 id="heading-which-ruby-do-you-have">Which Ruby do you have?</h2>
<p>MacOS comes with a "system Ruby" pre-installed.</p>
<p>Use the <code>which</code> command to see where Ruby is installed:</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">which</span> ruby
/usr/bin/ruby
</code></pre>
<p>If you see <code>/usr/bin/ruby</code>, it is the pre-installed macOS system Ruby.</p>
<p>It's fine to use the system Ruby for running sysadmin scripts, as long as you don't alter the system Ruby by attempting to update it or add gems. </p>
<p>But you don't want to use it when you are developing projects in Ruby.</p>
<h2 id="heading-ruby-for-development">Ruby for development</h2>
<p>For developing projects with Ruby, you should <a target="_blank" href="https://mac.install.guide/ruby/12.html">Install Ruby with Homebrew</a> or use a version manager such as asdf, chruby, rbenv, or rvm. </p>
<p>A version manager helps if you're juggling multiple projects and can't update all at once. For a guide that compares version managers and shows the best way to install Ruby, see my article <a target="_blank" href="https://mac.install.guide/ruby/index.html">Install Ruby on a Mac</a>.</p>
<p>But why not use the macOS default Ruby? Let's take a look at the reasons why it's a bad idea to use the Mac default Ruby for development.</p>
<h3 id="heading-gem-installation-hassles">Gem installation hassles</h3>
<p>RubyGems are the ready-made software libraries that make development easy and fun in Ruby. Most Ruby projects use at least a few gems.</p>
<p>If you use the Mac system Ruby, running <code>gem install</code> will try to save gems to the system Ruby directory <code>/Library/Ruby/Gems/2.6.0</code>. That directory is owned by <code>root</code>, the system superuser. Ordinary users are not allowed to write to it (and you really shouldn't alter this folder).</p>
<p>If you try to install a gem, for example <code>gem install rails</code>, you'll get a permissions error:</p>
<pre><code class="lang-bash">ERROR: While executing gem ... (Gem::FilePermissionError)
You don<span class="hljs-string">'t have write permissions for the /Library/Ruby/Gems/2.6.0 directory</span>
</code></pre>
<h3 id="heading-it-violates-system-security">It violates system security</h3>
<p>Unix-based systems are powerful, so there's a workaround. You can install gems as a superuser to override the permissions restriction. But don't do this!</p>
<pre><code class="lang-bash">$ sudo gem install rails
</code></pre>
<p>Any time you are about to run <code>sudo</code>, you should stop and ask if you're about to shoot yourself in the foot. </p>
<p>In this case, you need <code>sudo</code> because you're altering system files that are managed by the OS. Don't do it! You may leave the system in a broken or compromised state. Even worse, a gem might contain malicious code that tampers with your computer.</p>
<h3 id="heading-gem-management">Gem management</h3>
<p>Experienced developers use <a target="_blank" href="https://bundler.io/">Bundler</a> to install gems and manage their dependencies. </p>
<p>Imagine you've got projects that use different versions of a gem (maybe there was a new gem release between your projects). Or maybe two different gems in your project rely on different versions of a dependent gem. </p>
<p>Bundler uses a Gemfile in your project directory to keep track of the gems you need. If you were to use <code>sudo</code> to install gems with the system Ruby, you'd end up with a mess of incompatible gems in the system Ruby directory. </p>
<p>You can work around the systems permission problem by <a target="_blank" href="https://bundler.io/doc/troubleshooting.html">installing Bundler</a> with a command that uses your home directory for gems. But it's easier to install Ruby with Homebrew or use a version manager and use the Bundler that comes installed, which will correctly set up your local development environment.</p>
<h3 id="heading-use-the-newest-ruby">Use the newest Ruby</h3>
<p>When you start a project, use the newest Ruby release (it's 3.0 at the time this was written). </p>
<p>The system Ruby in macOS Catalina or Big Sur is Ruby 2.6.3, which is old. If you're just starting with Ruby, install with Homebrew and work on a project with Ruby 3.0. When you start building another project, it may be time to install a version manager so you can juggle projects with different Ruby versions.</p>
<h2 id="heading-macos-after-big-sur">MacOS after Big Sur</h2>
<p>MacOS Big Sur is now the current version. <a target="_blank" href="https://developer.apple.com/documentation/macos-release-notes/macos-catalina-10_15-release-notes">Apple says</a>:</p>
<blockquote>
<p><em>"Scripting language runtimes such as Python, Ruby, and Perl are included in macOS for compatibility with legacy software. Future versions of macOS won’t include scripting language runtimes by default, and might require you to install additional packages."</em></p>
</blockquote>
<p>If you're reading this at the end of 2021, the system Ruby may already be gone. If not, prepare yourself by installing Ruby with Homebrew or a version manager. </p>
<h2 id="heading-enjoy-ruby">Enjoy Ruby</h2>
<p>For developers planning to build web applications with Rails, I've written a guide, <a target="_blank" href="https://learn-rails.com/install-rails-mac/index.html">Install Rails on a Mac</a>, which goes beyond <a target="_blank" href="https://mac.install.guide/ruby/index.html">Install Ruby on a Mac</a> to show how to pick a version manager that will work with Node as well as Ruby.</p>
<p>Enjoy the pleasure of coding in Ruby! After all, it is known as a language dedicated to programmer happiness. But remember, the system Ruby is there for macOS, not for you.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Install Rails on Ubuntu and Update Ruby to the Latest Version ]]>
                </title>
                <description>
                    <![CDATA[ By Adebola Adeniran A couple of months ago, when I learned Ruby-on-Rails for the first time, I had to work on a collaborative project with a coding partner. We kept running into issues, as he had a different version of Rails and Buby setup for the pr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-install-rails-on-ubuntu-and-update-ruby-to-the-latest-version/</link>
                <guid isPermaLink="false">66d45d5d51f567b42d9f840f</guid>
                
                    <category>
                        <![CDATA[ Rails ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ubuntu ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 01 Jul 2020 12:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/Slice-3-1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Adebola Adeniran</p>
<p>A couple of months ago, when I learned Ruby-on-Rails for the first time, I had to work on a collaborative project with a coding partner. We kept running into issues, as he had a different version of Rails and Buby setup for the project. I couldn't wrap my head around how to install the versions the project needed. </p>
<p>Here's the guide I wish I had. It also shows you how to switch the version of Ruby or Rails you're using, depending on the projects you're working on.</p>
<p>First, let's get the latest version of Ruby installed. To do this, we need to install a package called <strong>RVM - Ruby version manager.</strong> This package lets us install ANY version of Ruby on our Ubuntu machine and allows us to switch between versions.</p>
<p>All the code here will be run using the Ubuntu CLI/terminal.</p>
<h2 id="heading-installing-rvm">Installing RVM</h2>
<ol>
<li>First, we need to install a pre-requisite. Open up your Ubuntu terminal and type the command:</li>
</ol>
<pre><code>sudo apt-get install software-properties-common
</code></pre><p>Next, we need to add the <strong>PPA (Personal Package archive)</strong>. A PPA is how we get files distributed by developers that are yet to make it to the official Ubuntu package/app store. </p>
<p>It's also a way for developers to distribute the latest versions of their software while waiting for Ubuntu to test and publish that software in the official store.</p>
<pre><code>sudo apt-add-repository -y ppa:rael-gc/rvm
</code></pre><p>The command above adds the PPA to the list of locations we can download packages from on our Ubuntu machine.</p>
<p>Next, let's refresh our list of packages by running:</p>
<p><code>sudo apt-get update</code></p>
<p>Finally, let's install RVM itself.</p>
<pre><code>sudo apt-get install rvm
</code></pre><p>Now restart your terminal for your changes to take effect. Then, type <code>rvm version</code> and hit <code>enter</code> to check that rvm is installed. You should get a response like this:</p>
<p><code>rvm 1.29.10 (manual) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [[https://rvm.io](https://rvm.io)]</code></p>
<h2 id="heading-installing-ruby">Installing Ruby</h2>
<p>Now we can install the latest Ruby version which is 2.7.1. Run the command <code>rvm install 2.7.1</code>. Alternatively, you can run <code>rvm install ruby</code> which will install the latest stable version (this will install v2.7.0).  </p>
<p>To see what Ruby versions you have installed, run <code>rvm ls</code>. To switch between Ruby versions, run <code>rvm use &lt;version_number&gt;</code> (for example, <code>rvm use 2.7.1</code>).</p>
<h2 id="heading-installing-ruby-on-rails">Installing Ruby-on-Rails</h2>
<p>The latest version of Rails is at 6.03. Rails is simply a Ruby gem, and with Ruby installed we can install Rails! Run <code>gem install rails</code> to install the latest version of Rails.  </p>
<p>Finally, to check that all went well, run <code>rails -v</code>. You should get <code>Rails 6.0.3.2</code> back, as this is the latest version at the time of publishing this article.   </p>
<p>You can now start your first Rails project by typing <code>rails new myapp</code>.</p>
<p>Hey, you're now on Rails!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Ruby Number Methods and Number Operations (with Examples) ]]>
                </title>
                <description>
                    <![CDATA[ Number methods in Ruby Ruby provides a variety of built-in methods you may use on numbers. The following is an incomplete list of integer and float methods. Even: Use .even? to check whether or not an integer is even. Returns a true or false boolean.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ruby-number-methods-integer-and-float-methods-with-examples/</link>
                <guid isPermaLink="false">66c35e1aadd0807b8e3fb91a</guid>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 21 Feb 2020 23:10:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c76740569d1a4ca3253.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-number-methods-in-ruby">Number methods in Ruby</h2>
<p>Ruby provides a variety of built-in methods you may use on numbers. The following is an incomplete list of <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html">integer</a> and <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil">float</a> methods.</p>
<h3 id="heading-evenhttpsruby-docorgcore-220integerhtmlmethod-i-even-3f"><a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html#method-i-even-3F">Even</a>:</h3>
<p>Use <code>.even?</code> to check whether or not an <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a> is even. Returns a <code>true</code> or <code>false</code> <strong>boolean</strong>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">15</span>.even? <span class="hljs-comment">#=&gt; false</span>
    <span class="hljs-number">4</span>.even?  <span class="hljs-comment">#=&gt; true</span>
</code></pre>
<h3 id="heading-oddhttpsruby-docorgcore-220integerhtmlmethod-i-odd-3f"><a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html#method-i-odd-3F">Odd</a>:</h3>
<p>Use <code>.odd?</code> to check whether or not an <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a> is odd. Returns a <code>true</code> or <code>false</code> <strong>boolean</strong>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">15</span>.odd? <span class="hljs-comment">#=&gt; true</span>
    <span class="hljs-number">4</span>.odd?  <span class="hljs-comment">#=&gt; false</span>
</code></pre>
<h3 id="heading-ceilhttpsruby-docorgcore-220floathtmlmethod-i-ceil"><a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil">Ceil</a>:</h3>
<p>The <code>.ceil</code> method rounds <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil"><strong>floats</strong></a> <strong>up</strong> to the nearest number. Returns an <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">8.3</span>.ceil <span class="hljs-comment">#=&gt; 9</span>
    <span class="hljs-number">6.7</span>.ceil <span class="hljs-comment">#=&gt; 7</span>
</code></pre>
<h3 id="heading-floorhttpsruby-docorgcore-220floathtmlmethod-i-floor"><a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html#method-i-floor">Floor</a>:</h3>
<p>The <code>.floor</code> method rounds <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil"><strong>floats</strong></a> <strong>down</strong> to the nearest number. Returns an <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">8.3</span>.floor <span class="hljs-comment">#=&gt; 8</span>
    <span class="hljs-number">6.7</span>.floor <span class="hljs-comment">#=&gt; 6</span>
</code></pre>
<h3 id="heading-nexthttpsruby-docorgcore-220integerhtmlmethod-i-next"><a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html#method-i-next">Next</a>:</h3>
<p>Use <code>.next</code> to return the next consecutive <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">15</span>.<span class="hljs-keyword">next</span> <span class="hljs-comment">#=&gt; 16</span>
    <span class="hljs-number">2</span>.<span class="hljs-keyword">next</span>  <span class="hljs-comment">#=&gt; 3</span>
    -<span class="hljs-number">4</span>.<span class="hljs-keyword">next</span> <span class="hljs-comment">#=&gt; -3</span>
</code></pre>
<h3 id="heading-predhttpsruby-docorgcore-187integerhtmlmethod-i-pred"><a target="_blank" href="https://ruby-doc.org/core-1.8.7/Integer.html#method-i-pred">Pred</a>:</h3>
<p>Use <code>.pred</code> to return the previous consecutive <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">15</span>.pred <span class="hljs-comment">#=&gt; 14</span>
    <span class="hljs-number">2</span>.pred  <span class="hljs-comment">#=&gt; 1</span>
    (-<span class="hljs-number">4</span>).pred <span class="hljs-comment">#=&gt; -5</span>
</code></pre>
<h3 id="heading-to-stringhttpsruby-docorgcore-242objecthtmlmethod-i-tos"><a target="_blank" href="https://ruby-doc.org/core-2.4.2/Object.html#method-i-to_s">To String</a>:</h3>
<p>Using <code>.to_s</code> on a number (<a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a>, <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil"><strong>floats</strong></a>, etc.) returns a <a target="_blank" href="https://ruby-doc.org/core-2.2.0/String.html">string</a> of that number.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">15</span>.to_s  <span class="hljs-comment">#=&gt; "15"</span>
    <span class="hljs-number">3.4</span>.to_s <span class="hljs-comment">#=&gt; "3.4"</span>
</code></pre>
<h3 id="heading-greatest-common-denominatorhttpsruby-docorgcore-220integerhtmlmethod-i-gcd"><a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html#method-i-gcd">Greatest Common Denominator</a>:</h3>
<p>The <code>.gcd</code> method provides the greatest common divisor (always positive) of two numbers. Returns an <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">15</span>.gcd(<span class="hljs-number">5</span>) <span class="hljs-comment">#=&gt; 5</span>
    <span class="hljs-number">3</span>.gcd(-<span class="hljs-number">7</span>) <span class="hljs-comment">#=&gt; 1</span>
</code></pre>
<h3 id="heading-roundhttpruby-docorgcore-220integerhtmlmethod-i-round"><a target="_blank" href="http://ruby-doc.org/core-2.2.0/Integer.html#method-i-round">Round</a>:</h3>
<p>Use <code>.round</code> to return a rounded <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Integer.html"><strong>integer</strong></a> or <a target="_blank" href="https://ruby-doc.org/core-2.2.0/Float.html"><strong>float</strong></a>.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">1</span>.round        <span class="hljs-comment">#=&gt; 1</span>
    <span class="hljs-number">1</span>.round(<span class="hljs-number">2</span>)     <span class="hljs-comment">#=&gt; 1.0</span>
    <span class="hljs-number">15</span>.round(-<span class="hljs-number">1</span>)   <span class="hljs-comment">#=&gt; 20</span>
</code></pre>
<h3 id="heading-timeshttpruby-docorgcore-220integerhtmlmethod-i-times"><a target="_blank" href="http://ruby-doc.org/core-2.2.0/Integer.html#method-i-times">Times</a>:</h3>
<p>Use <code>.times</code> to iterate the given block <code>int</code> times.</p>
<pre><code class="lang-ruby">    <span class="hljs-number">5</span>.times <span class="hljs-keyword">do</span> <span class="hljs-params">|i|</span>
      print i, <span class="hljs-string">" "</span>
    <span class="hljs-keyword">end</span>
    <span class="hljs-comment">#=&gt; 0 1 2 3 4</span>
</code></pre>
<h2 id="heading-math-operations-in-ruby">Math operations in Ruby</h2>
<p>In Ruby you can perform all standard math operations on numbers, including: addition <code>+</code>, subtraction <code>-</code>, multiplication <code>*</code>, division <code>/</code>, find remainders <code>%</code>, and work with exponents <code>**</code>.</p>
<h3 id="heading-addition">Addition:</h3>
<p>Numbers can be added together using the <code>+</code> operator.</p>
<pre><code class="lang-ruby"><span class="hljs-number">15</span> + <span class="hljs-number">25</span> <span class="hljs-comment">#=&gt; 40</span>
</code></pre>
<h3 id="heading-subtraction">Subtraction:</h3>
<p>Numbers can be subtracted from one another using the <code>-</code> operator.</p>
<pre><code class="lang-ruby"><span class="hljs-number">25</span> - <span class="hljs-number">15</span> <span class="hljs-comment">#=&gt; 10</span>
</code></pre>
<h3 id="heading-multiplication">Multiplication:</h3>
<p>Numbers can be multiplied together using the <code>*</code> operator.</p>
<pre><code class="lang-ruby"><span class="hljs-number">10</span> * <span class="hljs-number">5</span> <span class="hljs-comment">#=&gt; 50</span>
</code></pre>
<h3 id="heading-division">Division:</h3>
<p>Numbers can be divided by one another using the <code>/</code> operator.</p>
<pre><code class="lang-ruby"><span class="hljs-number">10</span> / <span class="hljs-number">5</span> <span class="hljs-comment">#=&gt; 2</span>
</code></pre>
<h3 id="heading-remainders">Remainders:</h3>
<p>Remainders can be found using the modulus <code>%</code> operator.</p>
<pre><code class="lang-ruby"><span class="hljs-number">10</span> % <span class="hljs-number">3</span> <span class="hljs-comment">#=&gt; 1 # because the remainder of 10/3 is 1</span>
</code></pre>
<h3 id="heading-exponents">Exponents:</h3>
<p>Exponents can be calculated using the <code>**</code> operator.</p>
<pre><code class="lang-ruby"><span class="hljs-number">2</span> ** <span class="hljs-number">3</span> <span class="hljs-comment">#=&gt; 8 # because 2 to the third power, or 2 * 2 * 2 = 8</span>
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manage Your Ruby Versions ]]>
                </title>
                <description>
                    <![CDATA[ Ruby has changed over time Ruby has been in constant development since the 1990s. And like many languages, there have been syntax changes across versions. This means that it is important to be clear about which Ruby version your code expects. Probabl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-manage-your-ruby-versions/</link>
                <guid isPermaLink="false">66c353a169cdcb77cd98a59b</guid>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 15 Feb 2020 22:26:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c91740569d1a4ca32f1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-ruby-has-changed-over-time"><strong>Ruby has changed over time</strong></h2>
<p>Ruby has been in constant development since the 1990s. And like many languages, there have been syntax changes across versions. This means that it is important to be clear about which Ruby version your code expects.</p>
<p>Probably the most visible change came with Ruby 1.9. Previously, we wrote hashes like this:</p>
<pre><code class="lang-ruby">  { <span class="hljs-symbol">:one</span> =&gt; <span class="hljs-number">1</span>, <span class="hljs-symbol">:two</span> =&gt; <span class="hljs-number">2</span>, <span class="hljs-symbol">:three</span> =&gt; <span class="hljs-number">3</span> }
</code></pre>
<p>This use of the ‘hashrocket’ operator (<code>=&gt;</code>) was so common, that Ruby 1.9 provided a shorthand:</p>
<pre><code class="lang-text">  { one: 1, two: 2, three: 3 }
</code></pre>
<p>This older code will run on any version, but the newer syntax will only run on Ruby 1.9+.</p>
<h2 id="heading-how-does-this-cause-problems"><strong>How does this cause problems?</strong></h2>
<p>For example, you might have decided to use a Gem which internally relies on Ruby 1.9 features. This means that your project now also relies on Ruby 1.9 features.</p>
<p>If you don’t specify which version of Ruby your project needs, it can be very confusing when code works on one machine, but not another.</p>
<p>As with most languages, it’s considered good practice to specify the version of Ruby that your code expects. This makes it much easier to manage multiple projects on your development machine, each expecting a different version of Ruby.</p>
<h2 id="heading-how-do-i-specify-my-ruby-version"><strong>How do I specify my Ruby version?</strong></h2>
<p>There are a couple of tools which are popular for this, but both have agreed to share a common file. Many Ruby (or Rails) projects will include a simple <code>.ruby-version</code> file, which simply specifies a version number, for example:</p>
<pre><code class="lang-text">2.4.2
</code></pre>
<p>Popular tools to help you manage your Ruby version are:</p>
<ul>
<li><a target="_blank" href="https://rvm.io/">Ruby Version Manager (RVM)</a></li>
<li><a target="_blank" href="https://github.com/rbenv/rbenv">rbenv</a></li>
</ul>
<p>Let’s look at RVM.</p>
<h3 id="heading-using-rvm"><strong>Using RVM</strong></h3>
<p>RVM is typically installed (<a target="_blank" href="https://rvm.io/">link</a>) on a Linux, Unix or MacOS machine. It is very convenient because it hooks into the <code>cd</code> (<code>c</code>hange <code>d</code>irectory) command. So when you move to a new project, your <code>.ruby-version</code> is read automatically, and you’re automatically switched to the correct version of Ruby before you start working.</p>
<p>For example, you might have this sequence:</p>
<pre><code class="lang-shell">% cd ~/projects/older-project
% ruby --version

ruby 2.3.5p376 (2017-09-14 revision 59905) [x86_64-darwin16]

% cd ~/projects/newer-project
% ruby --version

ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]
</code></pre>
<p>(These examples are from a MacOS machine).</p>
<h2 id="heading-other-info-on-ruby">Other info on Ruby:</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/introduction-to-object-oriented-programming-with-ruby-d594e1c6eebe/">An intro to Object-oriented Programming with Ruby</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/62edc7d6-1ec8-4e6b-ab42-51136a3b7073/">Most common Ruby array methods you should know</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Data Types in Ruby - True, False, and Nil Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ true, false, and nil are special built-in data types in Ruby. Each of these keywords evaluates to an object that is the sole instance of its respective class. true.class  => TrueClass false.class  => FalseClass nil.class  => NilClass true and false ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/data-types-in-ruby-true-false-and-nil-explained-with-examples/</link>
                <guid isPermaLink="false">66c348ab3a31d2480bb383aa</guid>
                
                    <category>
                        <![CDATA[ Boolean ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9cf8740569d1a4ca352a.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><code>true</code>, <code>false</code>, and <code>nil</code> are special built-in data types in Ruby. Each of these keywords evaluates to an object that is the sole instance of its respective class.</p>
<pre><code class="lang-ruby"><span class="hljs-literal">true</span>.<span class="hljs-keyword">class</span>
 =&gt; TrueClass
<span class="hljs-literal">false</span>.<span class="hljs-keyword">class</span>
 =&gt; FalseClass
<span class="hljs-literal">nil</span>.<span class="hljs-keyword">class</span>
 =&gt; NilClass
</code></pre>
<p><code>true</code> and <code>false</code> are Ruby’s native boolean values. A boolean value is a value that can only be one of two possible values: true or not true. The object <code>true</code> represents truth, while <code>false</code> represents the opposite. You can assign variables to <code>true</code> / <code>false</code>, pass them to methods, and generally use them as you would other objects (such as numbers, Strings, Arrays, Hashes).</p>
<p><code>nil</code> is a special value that indicates the absence of a value – it is Ruby’s way of referring to “nothing”. An example of when you will encounter the <code>nil</code> object is when you ask for something that doesn’t exist or cannot be found:</p>
<pre><code class="lang-ruby">hats = [<span class="hljs-string">"beret"</span>, <span class="hljs-string">"sombrero"</span>, <span class="hljs-string">"beanie"</span>, <span class="hljs-string">"fez"</span>, <span class="hljs-string">"flatcap"</span>]

hats[<span class="hljs-number">0</span>]
 =&gt; <span class="hljs-string">"beret"</span> <span class="hljs-comment"># the hat at index 0</span>
hats[<span class="hljs-number">2</span>]
 =&gt; <span class="hljs-string">"beanie"</span> <span class="hljs-comment"># the hat at index 2</span>
hats[<span class="hljs-number">4</span>]
 =&gt; <span class="hljs-string">"flatcap"</span> <span class="hljs-comment"># the hat at index 4</span>
hats[<span class="hljs-number">5</span>]
 =&gt; nil <span class="hljs-comment"># there is no hat at index 5, index 5 holds nothing (nil)</span>
</code></pre>
<p>Zero is not nothing (it’s a number, which is something). Likewise, empty strings, arrays, and hashes are not nothing (they are objects, which happen to be empty). You can call the method <code>nil?</code> to check whether an object is nil.</p>
<pre><code class="lang-ruby"><span class="hljs-number">0</span>.<span class="hljs-literal">nil</span>?
 =&gt; <span class="hljs-literal">false</span>
<span class="hljs-string">""</span>.<span class="hljs-literal">nil</span>?
 =&gt; <span class="hljs-literal">false</span>
[].<span class="hljs-literal">nil</span>?
 =&gt; <span class="hljs-literal">false</span>
{}.<span class="hljs-literal">nil</span>?
 =&gt; <span class="hljs-literal">false</span>
<span class="hljs-literal">nil</span>.<span class="hljs-literal">nil</span>?
 =&gt; <span class="hljs-literal">true</span>
 <span class="hljs-comment"># from the example above</span>
hats[<span class="hljs-number">5</span>].<span class="hljs-literal">nil</span>?
 =&gt; <span class="hljs-literal">true</span>
</code></pre>
<p>Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, <em>only</em> <code>false</code> and <code>nil</code> are “falsey,” everything else is “truthy.”</p>
<h2 id="heading-more-information">More Information:</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learning-ruby-from-zero-to-hero-90ad4eecc82d/">Learning Ruby: From Zero to Hero</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/idiomatic-ruby-writing-beautiful-code-6845c830c664/">Idiomatic Ruby: writing beautiful code</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/export-a-database-table-to-csv-using-a-simple-ruby-script-2/">How to Export a Database Table to CSV Using a Simple Ruby Script</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Ruby on Rails Explained ]]>
                </title>
                <description>
                    <![CDATA[ Ruby on Rails is a server-side framework (gem) built on the Ruby language to make websites. It includes everything you need to build web applications and has a big community. Ruby on Rails is an opinionated framework, and emphasizes the use of conven... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ruby-on-rails-explained/</link>
                <guid isPermaLink="false">66c35e1c39357f944697661f</guid>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby on Rails ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9cff740569d1a4ca3552.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="http://rubyonrails.org/">Ruby on Rails</a> is a server-side framework (gem) built on the Ruby language to make websites. It includes everything you need to build web applications and has a big community.</p>
<p>Ruby on Rails is an opinionated framework, and emphasizes the use of convention over configuration (CoC), and don't repeat yourself (DRY) practices. Rails can best be described as a model-view-controller (MVC) framework, and provides sensible defaults and structures for rapid application development. Lately, Rails has integrated an API module to make the creation of web-services faster and easier.</p>
<p>Ruby on Rails was created by David Heinemeir Hansson and is currently on it’s 6th version.</p>
<h2 id="heading-how-to-install-rails"><strong>How to install Rails</strong></h2>
<p>Rails is downloaded in the same way as any other Ruby gem: with the <code>gem install</code> command. Before we download it, we’ll need to <a target="_blank" href="https://www.ruby-lang.org/">download Ruby</a>. Afterwards we’re only 3 words away from starting with Ruby on Rails:</p>
<pre><code class="lang-shell">$ gem install rails
</code></pre>
<p>Rails ships with sqlite3 as the default database, which is a simple file on disk. You need to install MySQL or PostgreSQL if you want to use something more robust.</p>
<h2 id="heading-how-to-create-a-rails-application"><strong>How to create a Rails application</strong></h2>
<ol>
<li>After you install Ruby on Rails, it’s very simple to create a brand new application, we’ll just need 3 more words:</li>
</ol>
<pre><code class="lang-shell">$ rails new your_application_name
</code></pre>
<ol start="2">
<li>If you want to use MySQL:</li>
</ol>
<pre><code class="lang-shell">$ rails new &lt;application_name&gt; -d mysql
</code></pre>
<ol start="3">
<li>If you want to use Postgres:</li>
</ol>
<pre><code class="lang-shell">$ rails new &lt;application_name&gt; -d postgresql
</code></pre>
<ol start="4">
<li>This command will create a folder with the _your_application<em>name</em> you informed in the last command. Next step is to go to the new directory you’ve just created:</li>
</ol>
<pre><code class="lang-shell">$ cd your_application_name
</code></pre>
<ol start="5">
<li>Get the necessary gems and software packages before running your application:</li>
</ol>
<pre><code class="lang-shell">$ bundle install
</code></pre>
<ol start="6">
<li>To run the rails server and see if everything went accordingly is also fast:</li>
</ol>
<pre><code class="lang-shell">$ rails server
</code></pre>
<p>It couldn’t be anymore simple! Well, this isn’t actually 100% true, we could make it even smaller by reducing the <code>rails server</code> command to:</p>
<pre><code class="lang-shell">$ rails s
</code></pre>
<ol start="7">
<li>Now with your preferred browser, go to <code>http://localhost:3000</code> and you’ll see: “Yay! You’re on Rails!”</li>
</ol>
<h3 id="heading-alternative-method-for-creating-a-rails-application"><strong>Alternative method for creating a Rails application</strong></h3>
<ol>
<li>Create a new directory:</li>
</ol>
<pre><code class="lang-shell">$ mkdir &lt;application_name&gt;
</code></pre>
<ol start="2">
<li>Go into the new directory:</li>
</ol>
<pre><code class="lang-shell">$ cd &lt;application_name&gt;
</code></pre>
<ol start="3">
<li>Create the Rails application using the Unix dot notation. This results in assigning the name of the directory to the new application:</li>
</ol>
<pre><code class="lang-shell">$ rails new .
</code></pre>
<ol start="4">
<li>Start exploring the framework of the application you just created. To see a useful table of the folder structure, check out <a target="_blank" href="https://guides.rubyonrails.org/getting_started.html">Getting Started with Rails</a>.</li>
</ol>
<h2 id="heading-convention-over-configuration"><strong>Convention over Configuration</strong></h2>
<p><em>Convention over Configuration</em> means a developer only needs to specify unconventional aspects of the application. For example, if there is a class <code>Sale</code> in the model, the corresponding table in the database is called <code>sales</code> by default. It is only if one deviates from this convention, such as calling the table “products sold”, that the developer needs to write code regarding these names. Generally, Ruby on Rails conventions lead to less code and less repetition.</p>
<h2 id="heading-what-is-mvc"><strong>What is MVC?</strong></h2>
<p>Model (Active record) contains the business logic and interacts with the database. Views (Action views) all of the HTML files and structure. Controller (Action controller) interacts with the views and model to direct the actions of the application.</p>
<h2 id="heading-dry-dont-repeat-yourself"><strong>DRY - Don’t Repeat Yourself</strong></h2>
<p><em>Don’t repeat yourself</em> means that information is located in a single, unambiguous place. For example, using the ActiveRecord module of Rails, the developer does not need to specify database column names in class definitions. Instead, Ruby on Rails can retrieve this information from the database based on the class name.</p>
<h2 id="heading-ruby-on-rails-is-open-source"><strong>Ruby on Rails is open source</strong></h2>
<p>Not only is it free to use, you can also help make it better. More than 4,500 people have already contributed code to <a target="_blank" href="https://github.com/rails/rails">Rails</a>. It’s easier than you think to become one of them.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Ruby String Methods Explained - Length, Empty, and Other Built-In Methods ]]>
                </title>
                <description>
                    <![CDATA[ Ruby has many built in methods to work with strings. Strings in Ruby by default are mutable and can be changed in place or a new string can be returned from a method. Length The .length property returns the number of characters in a string including ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ruby-string-methods-explained-length-empty-and-other-built-in-methods/</link>
                <guid isPermaLink="false">66c35e1f39357f9446976621</guid>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9cf1740569d1a4ca350a.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Ruby has many built in methods to work with strings. Strings in Ruby by default are mutable and can be changed in place or a new string can be returned from a method.</p>
<h2 id="heading-length">Length</h2>
<p>The <code>.length</code> property returns the number of characters in a string including white-space.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello"</span>.length <span class="hljs-comment">#=&gt; 5</span>
<span class="hljs-string">"Hello World!"</span>.length <span class="hljs-comment">#=&gt; 12</span>
</code></pre>
<h2 id="heading-empty">Empty</h2>
<p>The <code>.empty?</code> method returns <code>true</code> if a string has a length of zero.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello"</span>.empty? <span class="hljs-comment">#=&gt; false</span>
<span class="hljs-string">"!"</span>.empty?     <span class="hljs-comment">#=&gt; false</span>
<span class="hljs-string">" "</span>.empty?     <span class="hljs-comment">#=&gt; false</span>
<span class="hljs-string">""</span>.empty?      <span class="hljs-comment">#=&gt; true</span>
</code></pre>
<h2 id="heading-count">Count</h2>
<p>The <code>.count</code> method counts how many times a specific character(s) is found in a string.</p>
<p>This method is case-sensitive.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"HELLO"</span>.count(<span class="hljs-string">'L'</span>) <span class="hljs-comment">#=&gt; 2</span>
<span class="hljs-string">"HELLO WORLD!"</span>.count(<span class="hljs-string">'LO'</span>) <span class="hljs-comment">#=&gt; 1</span>
</code></pre>
<h2 id="heading-insert">Insert</h2>
<p>The <code>.insert</code> method inserts a string into another string before a given index.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello"</span>.insert(<span class="hljs-number">3</span>, <span class="hljs-string">"hi5"</span>) <span class="hljs-comment">#=&gt; Helhi5lo # "hi5" is inserted into the string right before the second 'l' which is at index 3</span>
</code></pre>
<h2 id="heading-upcase">Upcase</h2>
<p>The <code>.upcase</code> method transforms all letters in a string to uppercase.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello"</span>.upcase <span class="hljs-comment">#=&gt; HELLO</span>
</code></pre>
<h2 id="heading-downcase">Downcase</h2>
<p>The <code>.downcase</code> method transforms all letters in a string to lowercase.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello"</span>.downcase <span class="hljs-comment">#=&gt; hello</span>
</code></pre>
<h2 id="heading-swapcase">Swapcase</h2>
<p>The <code>.swapcase</code> method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"hELLO wORLD"</span>.swapcase <span class="hljs-comment">#=&gt; Hello World</span>
</code></pre>
<h2 id="heading-capitalize">Capitalize</h2>
<p>The <code>.capitalize</code> method make the first letter in a string uppercase and the rest of the string lowercase.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"HELLO"</span>.capitalize <span class="hljs-comment">#=&gt; Hello</span>
<span class="hljs-string">"HELLO, HOW ARE YOU?"</span>.capitalize <span class="hljs-comment">#=&gt; Hello, how are you?</span>
</code></pre>
<p><em>Note that the first letter is only capitalized if it is at the beginning of the string.</em> <code>ruby "-HELLO".capitalize #=&gt; -hello "1HELLO".capitalize #=&gt; 1hello</code></p>
<h2 id="heading-reverse">Reverse</h2>
<p>The <code>.reverse</code> method reverses the order of the characters in a string.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello World!"</span>.reverse <span class="hljs-comment">#=&gt; "!dlroW olleH"</span>
</code></pre>
<h2 id="heading-split">Split</h2>
<p>The <code>.split</code> takes a strings and <em>splits</em> it into an array, then returns the array.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Hello, how are you?"</span>.split <span class="hljs-comment">#=&gt; ["Hello,", "how", "are", "you?"]</span>
</code></pre>
<p>The default method splits the string based on whitespace, unless a different separator is provided (see second example).</p>
<pre><code class="lang-ruby"><span class="hljs-string">"H-e-l-l-o"</span>.split(<span class="hljs-string">'-'</span>) <span class="hljs-comment">#=&gt; ["H", "e", "l", "l", "o"]</span>
</code></pre>
<h2 id="heading-chop">Chop</h2>
<p>The <code>.chop</code> method removes the last character of the string.</p>
<p>A new string is returned, unless you use the <code>.chop!</code> method which mutates the original string.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"Name"</span>.chop <span class="hljs-comment">#=&gt; Nam</span>
</code></pre>
<pre><code class="lang-ruby">name = <span class="hljs-string">"Batman"</span>
name.chop
name == <span class="hljs-string">"Batma"</span> <span class="hljs-comment">#=&gt; false</span>
</code></pre>
<pre><code class="lang-ruby">name = <span class="hljs-string">"Batman"</span>
name.chop!
name == <span class="hljs-string">"Batma"</span> <span class="hljs-comment">#=&gt; true</span>
</code></pre>
<h2 id="heading-strip">Strip</h2>
<p>The <code>.strip</code> method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns (<code>\t</code>, <code>\n</code>, <code>\r</code>).</p>
<pre><code class="lang-ruby"><span class="hljs-string">"  Hello  "</span>.strip <span class="hljs-comment">#=&gt; Hello</span>
</code></pre>
<h2 id="heading-chomp">Chomp</h2>
<p>The <code>.chomp</code> method removes the last character in a string, only if it’s a carriage return or newline (<code>\r</code>, <code>\n</code>).</p>
<p>This method is commonly used with the <code>gets</code> command to remove returns from user input.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"hello\r"</span>.chomp <span class="hljs-comment">#=&gt; hello</span>
<span class="hljs-string">"hello\t"</span>.chomp <span class="hljs-comment">#=&gt; hello\t # because tabs and other whitespace remain intact when using `chomp`</span>
</code></pre>
<h2 id="heading-to-integer">To Integer</h2>
<p>The <code>.to_i</code> method converts a string to an integer.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"15"</span>.to_i <span class="hljs-comment">#=&gt; 15 # integer</span>
</code></pre>
<h2 id="heading-gsub">Gsub</h2>
<p><code>gsub</code> replaces every reference of the first parameter for the second parameter on a string.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"ruby is cool"</span>.gsub(<span class="hljs-string">"cool"</span>, <span class="hljs-string">"very cool"</span>) <span class="hljs-comment">#=&gt; "ruby is very cool"</span>
</code></pre>
<p><code>gsub</code> also accepts patterns (like <em>regexp</em>) as first parameter, allowing things like:</p>
<pre><code class="lang-ruby"><span class="hljs-string">"ruby is cool"</span>.gsub(<span class="hljs-regexp">/[aeiou]/</span>, <span class="hljs-string">"*"</span>) <span class="hljs-comment">#=&gt; "r*by *s c**l"</span>
</code></pre>
<h2 id="heading-concatenation">Concatenation</h2>
<p>Ruby implements some methods to concatenate two strings together.</p>
<p>The <code>+</code> method:</p>
<pre><code class="lang-ruby"><span class="hljs-string">"15"</span> + <span class="hljs-string">"15"</span> <span class="hljs-comment">#=&gt; "1515" # string</span>
</code></pre>
<p>The <code>&lt;&lt;</code> method:</p>
<pre><code class="lang-ruby"><span class="hljs-string">"15"</span> &lt;&lt; <span class="hljs-string">"15"</span> <span class="hljs-comment">#=&gt; "1515" # string</span>
</code></pre>
<p>The <code>concat</code> method:</p>
<pre><code class="lang-ruby"><span class="hljs-string">"15"</span>.concat <span class="hljs-string">"15"</span> <span class="hljs-comment">#=&gt; "1515" # string</span>
</code></pre>
<h2 id="heading-index">Index</h2>
<p>The <code>index</code> method returns the index position of the first occurrence of the substring or regular expression pattern match in a string. If there is no match found, <code>nil</code> is returned.</p>
<p>A second optional parameter indicates which index position in the string to begin searching for a match.</p>
<pre><code class="lang-ruby"><span class="hljs-string">"information"</span>.index(<span class="hljs-string">'o'</span>) <span class="hljs-comment">#=&gt; 3</span>
<span class="hljs-string">"information"</span>.index(<span class="hljs-string">'mat'</span>) <span class="hljs-comment">#=&gt; 5</span>
<span class="hljs-string">"information"</span>.index(<span class="hljs-regexp">/[abc]/</span>) <span class="hljs-comment">#=&gt; 6</span>
<span class="hljs-string">"information"</span>.index(<span class="hljs-string">'o'</span>, <span class="hljs-number">5</span>) <span class="hljs-comment">#=&gt; 9</span>
<span class="hljs-string">"information"</span>.index(<span class="hljs-string">'z'</span>) <span class="hljs-comment">#=&gt; nil</span>
</code></pre>
<h2 id="heading-clear">Clear</h2>
<p>Removes string content.</p>
<pre><code class="lang-ruby">a = <span class="hljs-string">"abcde"</span>
a.clear    <span class="hljs-comment">#=&gt; ""</span>
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Most Common Ruby Array Methods You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ Common Array Methods Ruby Arrays form a core foundation in programming in Ruby, and most languages in fact. It is used so much that it would be beneficial to know and even memorize some of the most commonly used methods for arrays. If you want to kno... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/common-array-methods-in-ruby/</link>
                <guid isPermaLink="false">66c3479d4f1fc448a3678fcd</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 27 Jan 2020 23:54:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d5f740569d1a4ca376c.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-common-array-methods"><strong>Common Array Methods</strong></h2>
<p>Ruby Arrays form a core foundation in programming in Ruby, and most languages in fact. It is used so much that it would be beneficial to know and even memorize some of the most commonly used methods for arrays. If you want to know more about Ruby Arrays, we have <a target="_blank" href="https://guide.freecodecamp.org/ruby/ruby-arrays">an article about them</a>.</p>
<p>For the purpose of this guide, our array will be as follows:</p>
<pre><code class="lang-ruby">array = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
</code></pre>
<h4 id="heading-length"><strong>.length</strong></h4>
<p>The .length method tallies the number of elements in your array and returns the count:</p>
<pre><code class="lang-ruby">array.length
=&gt; <span class="hljs-number">5</span>
</code></pre>
<h4 id="heading-first"><strong>.first</strong></h4>
<p>The .first method accesses the first element of the array, the element at index 0:</p>
<pre><code class="lang-ruby">array.first
=&gt; <span class="hljs-number">0</span>
</code></pre>
<h4 id="heading-last"><strong>.last</strong></h4>
<p>The .last method accesses the last element of the array:</p>
<pre><code class="lang-ruby">array.last
=&gt; <span class="hljs-number">4</span>
</code></pre>
<h4 id="heading-take"><strong>.take</strong></h4>
<p>The .take method returns the first n elements of the array:</p>
<pre><code class="lang-ruby">array.take(<span class="hljs-number">3</span>)
=&gt; [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
</code></pre>
<h4 id="heading-drop"><strong>.drop</strong></h4>
<p>The .drop method returns the elements after n elements of the array:</p>
<pre><code class="lang-ruby">array.drop(<span class="hljs-number">3</span>)
=&gt; [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
</code></pre>
<h4 id="heading-array-index"><strong>array index</strong></h4>
<p>You can access a specific element in an array by accessing its index. If the index does not exist in the array, nil will be returned:</p>
<pre><code class="lang-ruby">array[<span class="hljs-number">2</span>]
=&gt; <span class="hljs-number">2</span>

array[<span class="hljs-number">5</span>]
=&gt; nil
</code></pre>
<h4 id="heading-pop"><strong>.pop</strong></h4>
<p>The .pop method will permantently remove the last element of an array:</p>
<pre><code class="lang-ruby">array.pop
=&gt; [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
</code></pre>
<h4 id="heading-shift"><strong>.shift</strong></h4>
<p>The .shift method will permantently remove the first element of an array and return this element:</p>
<pre><code class="lang-ruby">array.shift
=&gt; <span class="hljs-number">0</span>  
array
=&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
</code></pre>
<h4 id="heading-push"><strong>.push</strong></h4>
<p>The .push method will allow you to add an element to the end of an array:</p>
<pre><code class="lang-ruby">array.push(<span class="hljs-number">99</span>)
=&gt; [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">99</span>]
</code></pre>
<h4 id="heading-unshift"><strong>.unshift</strong></h4>
<p>The .unshift method will allow you to add an element to the beginning of an array:</p>
<pre><code class="lang-text">array = [2, 3]
array.unshift(1)
=&gt; [1, 2, 3]
</code></pre>
<h4 id="heading-delete"><strong>.delete</strong></h4>
<p>The .delete method removes a specified element from an array permanently:</p>
<pre><code class="lang-ruby">array.delete(<span class="hljs-number">1</span>)
=&gt; [<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
</code></pre>
<h4 id="heading-deleteat"><strong>.delete_at</strong></h4>
<p>The .delete_at method allows you to permanently remove an element of an array at a specified index:</p>
<pre><code class="lang-ruby">array.delete_at(<span class="hljs-number">0</span>)
=&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
</code></pre>
<h4 id="heading-reverse"><strong>.reverse</strong></h4>
<p>The .reverse method reverses the array but does not mutate it (the original array stays as is):</p>
<pre><code class="lang-ruby">array.reverse
=&gt; [<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>]
</code></pre>
<h4 id="heading-select"><strong>.select</strong></h4>
<p>The .select method iterates over an array and returns a new array that includes any items that return true to the expression provided.</p>
<pre><code class="lang-ruby">array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]
array.select { <span class="hljs-params">|number|</span> number &gt; <span class="hljs-number">4</span> }
=&gt; [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]
array
=&gt; [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]
</code></pre>
<h4 id="heading-include"><strong>.include?</strong></h4>
<p>The include? method checks to see if the argument given is included in the array:</p>
<pre><code class="lang-ruby">array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
=&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
array.<span class="hljs-keyword">include</span>?(<span class="hljs-number">3</span>)
=&gt; true

<span class="hljs-comment">#### .flatten</span>
The flatten method can be used to take an array that contains nested arrays <span class="hljs-keyword">and</span> create a one-dimensional <span class="hljs-symbol">array:</span>

<span class="hljs-string">``</span><span class="hljs-string">` ruby
array = [1, 2, [3, 4, 5], [6, 7]]
array.flatten
=&gt; [1, 2, 3, 4, 5, 6, 7]</span>
</code></pre>
<h4 id="heading-join"><strong>.join</strong></h4>
<p>The .join method returns a string of all the elements of the array separated by a separator parameter. If the separator parameter is nil, the method uses an empty string as a separator between strings.</p>
<pre><code class="lang-ruby">array.join
=&gt; <span class="hljs-string">"1234"</span>
array.join(<span class="hljs-string">"*"</span>)
=&gt; <span class="hljs-string">"1*2*3*4"</span>
</code></pre>
<h4 id="heading-each"><strong>.each</strong></h4>
<p>The .each method iterates over each element of the array, allowing you to perform actions on them.</p>
<pre><code class="lang-ruby">array.each <span class="hljs-keyword">do</span> <span class="hljs-params">|element|</span>
  puts element
<span class="hljs-keyword">end</span>
=&gt; 
<span class="hljs-number">0</span>
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
</code></pre>
<h4 id="heading-map"><strong>.map</strong></h4>
<p>The .map method is the same as the .collect method. The .map and .collect methods iterate over each element of the array, allowing you to perform actions on them. The .map and .collect methods differ from the .each method in that they return an array containing the transformed elements.</p>
<pre><code class="lang-ruby">array.map { <span class="hljs-params">|element|</span> element * <span class="hljs-number">2</span> }
  puts element
<span class="hljs-keyword">end</span>
=&gt; 
<span class="hljs-number">0</span>
<span class="hljs-number">2</span>
<span class="hljs-number">4</span>
<span class="hljs-number">6</span>
<span class="hljs-number">8</span>
</code></pre>
<h4 id="heading-uniq"><strong>.uniq</strong></h4>
<p>The .uniq method takes in an array containing duplicate elements, and returns a copy of the array containing only unique elements—any duplicate elements are removed from the array.</p>
<pre><code class="lang-ruby">array = [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">4</span>, <span class="hljs-number">4</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]
array.uniq
=&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]
</code></pre>
<h4 id="heading-concat"><strong>.concat</strong></h4>
<p>The .concat method appends the elements from an array to the original array. The .concat method can take in multiple arrays as an argument, which will in turn append multiple arrays to the original array.</p>
<pre><code class="lang-ruby">array = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
array.concat([<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>], [<span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>])
=&gt; [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]
</code></pre>
<h2 id="heading-more-information"><strong>More Information</strong></h2>
<ul>
<li><a target="_blank" href="http://ruby-doc.org/core-2.5.1/Array.html">Ruby Array docs</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/six-ruby-array-methods-you-need-to-know-5f81c1e268ce/">Six Ruby array methods you need to know</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learning-ruby-from-zero-to-hero-90ad4eecc82d/">Learning Ruby - from Zero to Hero</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Export a Database Table to CSV Using a Simple Ruby Script ]]>
                </title>
                <description>
                    <![CDATA[ If you have a Rails project and want to export a table as a CSV, without having to go to all the trouble of finding a gem, installing and using it, then uninstalling it when it’s no longer needed, I have some good news. Here’s an easy and quick way ]]>
                </description>
                <link>https://www.freecodecamp.org/news/export-a-database-table-to-csv-using-a-simple-ruby-script-2/</link>
                <guid isPermaLink="false">66d45ee7d1ffc3d3eb89dddf</guid>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Fatos Morina ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2019 05:28:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9ca0cc740569d1a4ca4ada.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you have a Rails project and want to export a table as a CSV, without having to go to all the trouble of finding a gem, installing and using it, then uninstalling it when it’s no longer needed, I have some good news. Here’s an easy and quick way to export a particular table from your database as a CSV file.</p>
<p>This is the <a target="_blank" href="https://gist.github.com/foxumon/fdb30349545944eee58c7858e6bab23c">code</a> that you need to run. You can put it as a rake task and run it, or run it another way.</p>
<p>As you can see, first we import <code>CSV</code>— we need it to do the writing of the CSV file with the data from the database. We then choose the location and the name for the file that we want to export it to, which in our case will be a file called <em>data.csv</em> included under repository <em>public</em>.</p>
<p>Then we set the table that we want to export and start writing. We could also change the attributes that we want to export — we don’t have to include them all as they are in the database.</p>
<p>That’s it! It’s that simple and yet very helpful.</p>
<p><em>This article was originally published on</em> <a target="_blank" href="https://medium.com/better-programming/export-a-database-table-to-csv-using-a-simple-ruby-script-5577a0914eb0?source=friends_link&amp;sk=6debc0a92a8679247534b2e60a42f516"><em>Medium</em></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to get started: testing a Ruby-on-Rails / ReactJS app with RSpec, Jest and Enzyme ]]>
                </title>
                <description>
                    <![CDATA[ By Holly Atkinson I recently made a simple ideas board web app using ReactJS, Ruby-on-Rails and PostgreSQL. Below, I’ll walk you through the initial steps I took to set up basic unit tests for one of the features of my app, adding a new idea. _Photo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-started-testing-a-ruby-on-rails-reactjs-app-with-rspec-jest-and-enzyme-d058f415894e/</link>
                <guid isPermaLink="false">66d45f339208fb118cc6cfc1</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Jest ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 03 May 2019 17:55:33 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*KnkP0HAL3iL6tyTQo7jVZw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Holly Atkinson</p>
<p>I recently made a simple ideas board web app using ReactJS, Ruby-on-Rails and PostgreSQL. Below, I’ll walk you through the initial steps I took to set up basic unit tests for one of the features of my app, adding a new idea.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yToemQSqCMdhO5ADFrrEyf8WwRNFKWl2Zq69" alt="Image" width="800" height="571" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/awU3XEzdU94?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;Dan DeAlmeida on &lt;a href="https://unsplash.com/search/photos/ideas?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<p>Note: I’m not going to discuss the <em>scope</em> of tests in this post; rather, my focus is on understanding how to install some of the <em>dependencies</em> in order to be able to get started with writing the tests.</p>
<h3 id="heading-background-ideas-board-set-up">Background: ideas board set up</h3>
<p>I used Node package manager to manage my project’s dependencies. If you’d like to code along, you’ll need to make sure you have Node installed on your computer.</p>
<p><em>Project features</em></p>
<p><strong>In Rails</strong></p>
<p>Models: Idea</p>
<p>Relationships: none</p>
<p><strong>In React</strong></p>
<p>Components: Navbar, IdeasContainer, Idea</p>
<h3 id="heading-getting-started-with-rspec"><strong>Getting started with RSpec</strong></h3>
<p>I used RSpec to test the Rails part of my ideas board web app. To get started:</p>
<ol>
<li>I added the gem ‘rspec-rails’, ‘~&gt; 3.8’ to my gemfile.</li>
<li><p>I then ran <code>bundle</code> in my terminal window (making sure I was in the Rails directory).</p>
</li>
<li><p>Next, in my Rails directory, I created a new folder called <code>spec</code>. And then, another new folder inside that one called <code>requests</code>.</p>
</li>
<li><p>I created a new file called <code>ideas_spec.rb</code>. You can replace the name <code>ideas_spec</code> with the name of whichever model you want to test, making sure to include the <code>_spec</code> part to denote that it's a test file.</p>
</li>
<li><p>At the top of my ideas_spec.rb file, I added the following text:</p>
</li>
</ol>
<p><code>require ‘rails_helper’</code></p>
<ol start="6">
<li>Then, in the same file, I included code describing the first test I wanted to run:</li>
</ol>
<pre><code class="lang-ruby">describe “add an idea”, <span class="hljs-symbol">:type</span> =&gt; <span class="hljs-symbol">:request</span> dodescribe “add an idea”, <span class="hljs-symbol">:type</span> =&gt; <span class="hljs-symbol">:request</span> <span class="hljs-keyword">do</span>
before <span class="hljs-keyword">do</span>
 post ‘/api/v1/ideas’
<span class="hljs-keyword">end</span>
it ‘returns a created status’ <span class="hljs-keyword">do</span>
  expect(response).to have_http_status(<span class="hljs-number">201</span>)
<span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<ol start="7">
<li>To run my test, I typed <code>rspec</code> in my terminal window, making sure I was in my rails project directory.</li>
</ol>
<p>If you’ve been following along, RSpec should run at this point and your first test should pass!</p>
<h3 id="heading-getting-started-with-jest"><strong>Getting started with Jest</strong></h3>
<p>I was pleasantly surprised to find out that the testing framework Jest is included with create-react-app! However, I also wanted to use Enzyme, a testing utility, for which I needed to install some dependencies.</p>
<ol>
<li>To start off, I created a new folder called <code>_tests_</code> in my app’s <code>src</code> directory.</li>
<li>In my client-side directory, I ran the following commands:</li>
</ol>
<pre><code>npm i -D react-test-renderer
</code></pre><pre><code>npm install --save-dev jest-enzyme
</code></pre><pre><code>npm install --save-dev enzyme enzyme-adapter-react<span class="hljs-number">-16</span>
</code></pre><ol start="3">
<li>To configure Enzyme, I created a file in <code>src</code> called <code>setupTests.js</code> and included the following:</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Enzyme = <span class="hljs-built_in">require</span>(<span class="hljs-string">'enzyme'</span>);
<span class="hljs-keyword">const</span> EnzymeAdapter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'enzyme-adapter-react-16'</span>);
Enzyme.configure({ <span class="hljs-attr">adapter</span>: <span class="hljs-keyword">new</span> EnzymeAdapter() });
</code></pre>
<ol start="4">
<li><p>Inside my <code>_tests_</code> folder, I created a new file, called <code>App.tests.js</code></p>
</li>
<li><p>I included the following text at the top of this file to import my components and all the testing functionality I wanted for <em>all</em> my tests:</p>
</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'../App'</span>;
<span class="hljs-keyword">import</span> Idea <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Idea'</span>;
<span class="hljs-keyword">import</span> IdeasContainer <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/IdeasContainer'</span>;
<span class="hljs-keyword">import</span> { create, update } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-test-renderer'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'../setupTests'</span>;
<span class="hljs-keyword">import</span> { shallow, mount, render } <span class="hljs-keyword">from</span> <span class="hljs-string">'enzyme'</span>;
<span class="hljs-keyword">import</span> { shallowToJson } <span class="hljs-keyword">from</span> <span class="hljs-string">'enzyme-to-json'</span>;
</code></pre>
<ol start="6">
<li>Underneath, I included my <em>first</em> unit test:</li>
</ol>
<pre><code class="lang-ruby">describe(<span class="hljs-string">'Idea'</span>, () =&gt; {
  it(<span class="hljs-string">'should render a new idea correctly'</span>, () =&gt; {
    const output = shallow(
      &lt;Idea
      key=<span class="hljs-string">"mockKey"</span>
      idea={<span class="hljs-string">"1"</span>, <span class="hljs-string">"Test"</span>, <span class="hljs-string">"Test"</span>}
      onClick={<span class="hljs-string">"mockFn"</span>}
      delete={<span class="hljs-string">"mockFn2"</span>}
      /&gt;
    );
    expect(shallowToJson(output)).toMatchSnapshot();
  });
});
</code></pre>
<ol start="7">
<li><p>I ran <code>rails s</code> in the server side directory and then <code>npm start</code> in the client side directory to start my ideas board on localhost:3001.</p>
</li>
<li><p>To run my first test, I typed the following into my terminal window (making sure I was in the client directory):</p>
</li>
</ol>
<pre><code>npm run test
</code></pre><p>If you’ve been following along, Jest should run at this point, your test should pass — and you’re in a great place now to write more tests!</p>
<p>For more information on the ideas board project, my repo can be found <a target="_blank" href="https://github.com/atkinsonholly/tracr">here</a>.</p>
<p>If you made it this far, thanks for reading! I hope my post helped you get started with setting up your tests.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to Object-Oriented Programming with Ruby ]]>
                </title>
                <description>
                    <![CDATA[ By Saul Costa Object-oriented programming (OOP) is a programming paradigm organized around objects. At a high level, OOP is all about being able to structure code so that its functionality can be shared throughout the application. If done properly, O... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/introduction-to-object-oriented-programming-with-ruby-d594e1c6eebe/</link>
                <guid isPermaLink="false">66c35866d372f14b49bdcbb6</guid>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 26 Feb 2019 22:49:30 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*yk9cvq3T5pHUsObH3XiA1Q.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Saul Costa</p>
<p><strong>Object-oriented programming</strong> (<strong>OOP</strong>) is a programming paradigm organized around objects. At a high level, OOP is all about being able to structure code so that its functionality can be shared throughout the application. If done properly, OOP can lead to very elegantly written programs that have minimal code duplication.</p>
<p>This is opposed to procedural programming (PP), in which you build programs in sequential order and call methods when you want shared behavior between pages in the application. Common procedural programming languages include <a target="_blank" href="https://en.wikipedia.org/wiki/C_(programming_language)">C</a> and <a target="_blank" href="https://en.wikipedia.org/wiki/Go_(programming_language)">Go</a>.</p>
<p>In this tutorial, you’ll learn the fundamental concepts of OOP for <strong>Ruby</strong>, an object-oriented programming language wherein everything is an object. We will be using Ruby since one of its defining attributes — in addition to its elegant syntax and readability — is how it implements OOP techniques. This makes it a great language to start learning OOP with.</p>
<p>We will cover:</p>
<ul>
<li>Creating classes</li>
<li>Instantiating objects</li>
<li>Initializing arguments</li>
<li>Working with inheritance, and</li>
<li>Private and public methods.</li>
</ul>
<p>In learning these concepts, we will build out our own application: an API connector that communicates dynamically with an application that sends a text message. This will include walking through how to leverage concepts such as inheritance and object instantiation to make our code more scalable and reusable!</p>
<p><em>This brief tutorial is adapted from Next Tech’s <a target="_blank" href="https://c.next.tech/2EyLhYk">Introduction to Ruby course</a>, which includes an in-browser sandboxed environment and auto-checked interactive tasks to complete.</em></p>
<p><em>You can follow along with the code snippets in this tutorial using Next Tech’s sandbox which already has Ruby pre-installed. If you chose to use your own IDE, make sure Ruby is installed by following the instructions on the <a target="_blank" href="https://www.ruby-lang.org/en/documentation/installation/">installation page</a>.</em></p>
<h3 id="heading-creating-classes">Creating Classes</h3>
<p>Before we begin, let’s define what an <strong>object</strong> is. At its core, an object is a self-contained piece of code that contains data (“attributes”) and behavior (“methods”) and can communicate with other objects. Objects of the same type are created from <strong>classes</strong>, which act as blueprints that define properties and behavior.</p>
<p>Creating a class in Ruby is fairly easy. To define a class, simply type the <code>class</code> word followed by the name of the class, and end it with the <code>end</code> word. Anything contained between <code>class</code> and <code>end</code> belongs to this class.</p>
<p>Class names in Ruby have a very specific style requirement. They need to start with a letter and if they represent multiple words, each new word needs also to be an uppercase letter — i.e. “CamelCase”.</p>
<p>We’ll start by creating a class called <code>ApiConnector</code>:</p>
<p>Classes in Ruby can store both data and methods. In many traditional OOP languages such as Java, you need to create two methods for each data element you want to be included in the class. One method, the <strong>setter</strong>, sets the value in the class. The other method, the <strong>getter</strong>, allows you to retrieve the value.</p>
<p>The process of creating setter and getter methods for every data attribute can be tiresome and leads to incredibly long class definitions. Thankfully Ruby has a set of tools called <strong>attribute accessors</strong>.</p>
<p>Let’s implement some setters and getters for some new data elements for our class. Since it’s an API connector, it would make sense to have data elements such as <code>title</code>, <code>description</code>, and <code>url</code>. We can add these elements with the following code:</p>
<p>When you merely create a class, it doesn’t do anything — it is simply a definition. In order to work with the class, we need to create an instance of it…we’ll cover that next!</p>
<h3 id="heading-instantiation">Instantiation</h3>
<p>To understand what <strong>instantiation</strong> is, let’s consider a real-world analogy. Let’s imagine that you’re building a house. The first task is to build a blueprint for the house. This blueprint would contain attributes and features of the house, such as the dimensions for each room, how the plumbing will flow, and so on.</p>
<p>Is the blueprint of the house the actual house? Of course not, it simply lists out the attributes and design elements for how the home will be created. So after the blueprint is completed, the actual home can be built — or, “instantiated”.</p>
<p>As explained in the previous section, in OOP, a class is the blueprint for an object. It simply describes what an object will look like and how it will behave. Therefore, instantiation is the process of taking a class definition and creating an object that you can use in a program.</p>
<p>Let’s create a new instance of our <code>ApiConnector</code> class and store it in a variable called <code>api</code>:</p>
<p>Now that we have an object created, we can use the <code>api</code> variable to work with the class attributes. For example, we can run the code:</p>
<pre><code>[Out:]https:<span class="hljs-comment">//next.tech</span>
</code></pre><p>In addition to creating attributes, you can also create methods within a class:</p>
<p>To access this method, we can use the same syntax that we utilized with the attribute accessors:</p>
<p>Putting this all together, running the full class code below will result in the <code>url</code> and the <code>test_method</code> message to be printed:</p>
<pre><code>[Out:]<span class="hljs-string">"https://next.tech"</span><span class="hljs-string">"testing class call"</span>
</code></pre><h3 id="heading-initializer-method">Initializer Method</h3>
<p>One thing you may find handy in Ruby development is the ability to create an <strong>initializer</strong> method. This is simply a method called <code>initialize</code> that will run every time when you create an instance of your class. In this method, you can give values to your variables, call other methods, and do just about anything that you think should happen when a new instance of that class is created.</p>
<p>Let’s update our <code>ApiConnector</code> to utilize an initializer method:</p>
<p>Within the <code>initialize</code> method, we created an instance variable for each of the parameters so that we can use these variables in other parts of the application as well.</p>
<p>We also removed the <code>attr_accessor</code> method since the new <code>initialize</code> method will take care of this for us. If you need the ability to call the data elements outside of the class, then you would still need to have the <code>attr_accessor</code> call in place.</p>
<p>To test if the <code>initialize</code> method is working, let’s create another method within the class that prints these values out:</p>
<p>Finally, we’ll instantiate the class and test the initialize method:</p>
<pre><code>[Out:]<span class="hljs-string">"My title"</span><span class="hljs-string">"My cool description"</span><span class="hljs-string">"https://next.tech"</span>
</code></pre><h4 id="heading-working-with-optional-values">Working with optional values</h4>
<p>Now, what happens when we want to make one of these values optional? For example, what if we want to give a default value to the URL? To do that, we can update our <code>initialize</code> method with the following syntax:</p>
<p>Now our program will have the same output even if we don’t pass the <code>url</code> value while creating a new instance of the class:</p>
<h4 id="heading-using-named-arguments">Using named arguments</h4>
<p>Though this looks simple, passing arguments can get complex in real-world Ruby applications because some methods may take a large number of arguments. In such cases, it becomes difficult to know the order of arguments and what values to assign to them.</p>
<p>To avoid this confusion, you can utilize named arguments, like this:</p>
<p>You can enter the arguments without having to look at the order in the <code>initialize</code> method, and even change the order of the arguments without causing an error:</p>
<h4 id="heading-overriding-default-values">Overriding default values</h4>
<p>What happens if we want to override a default value? We simply update our instantiation call like this:</p>
<p>This update will override our default value of <code>https://next.tech</code>, and calling <code>api.testing_initializer</code> will now print <code>https://next.xyz</code> as the URL.</p>
<h3 id="heading-inheritance">Inheritance</h3>
<p>Now, we are going to learn about an important object-oriented principle called <strong>inheritance</strong>. Before going into how it is executed in Ruby, let’s see why it’s important for building applications.</p>
<p>To start with, inheritance means your classes can have a hierarchy. It is best used when different classes have some shared responsibilities, since it would be a poor practice to duplicate code in each class for identical or even similar behavior.</p>
<p>Take our <code>ApiConnector</code> class. Let's say we have different API classes for various platforms, but each class shares a number of common data or processes. Instead of duplicating code in each of the API connector classes, we can have one <strong>parent class</strong> with the shared data and methods. From there, we can create <strong>child classes</strong> from this parent class. With the way that inheritance works, each of the child classes will have access to the components provided from the parent class.</p>
<p>For example, say we have three APIs: <code>SmsConnector</code>, <code>PhoneConnector</code>, and <code>MailerConnector</code>. If we wrote code individually for each of these classes, it would look like this:</p>
<p>As you can see, we are simply repeating the same code across different classes. This is considered a poor programming practice that violates the <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> (Don’t Repeat Yourself) principle of development. Instead, we can make an <code>ApiConnector</code> parent class, and each of the other classes can inherit the common functionality from this class:</p>
<p>By leveraging inheritance, we were able to cut all of the duplicate code throughout our classes.</p>
<p>The syntax for using inheritance is to define the child class name, followed by the <code>&amp;</code>lt; symbol, then the parent class name — i.e. o<code>ur SmsConnec</code>to<code>r, MailerConnec</code>tor, a<code>nd PhoneConnec</code>tor classes inherit from t<code>he ApiConnec</code>tor class .</p>
<p>Each of these child classes now has access to the full set of elements provided in the parent <code>ApiConnector</code> class. For example, if we create a new instance of <code>SmsConnector</code> with the following parameters, we can call the <code>send_sms</code> method:</p>
<pre><code>[Out:]Sending SMS message <span class="hljs-keyword">with</span> the title <span class="hljs-string">'Hi there!'</span> and description <span class="hljs-string">'I'</span>m an SMS message<span class="hljs-string">'.</span>
</code></pre><p>A rule of thumb in OOP is to ensure that a class performs a single responsibility. For example, the <code>ApiConnector</code> class should not send SMS messages, make phone calls, or send emails since that would be three core responsibilities.</p>
<h3 id="heading-private-and-public-methods">Private and Public Methods</h3>
<p>Before we dive into private and public methods, let’s first go back to our original <code>ApiConnector</code> class and create a <code>SmsConnector</code> class that inherits from <code>ApiConnector</code>. In this class, we will create a method called <code>send_sms</code> that will run a script that contacts an API:</p>
<p>This method will send a <code>title</code> and <code>url</code> to an API, which will in turn send an SMS message. Now we can instantiate the <code>SmsConnector</code> class and call the <code>send_sms</code> message:</p>
<p>Running this code will contact the SMS API and send the message. You can go to the bottom of <a target="_blank" href="http://edutechional-smsy.herokuapp.com/notifications">this page</a> to see your message!</p>
<p>Now, using this example, let’s discuss the types of methods provided by classes.</p>
<p>The <code>send_sms</code> method is a <strong>public method</strong>. This means that anyone working on our class can communicate with this method. This may not seem like a big deal if you are working on an application that no one else is working on. However, if you build an API or code library that is open sourced for others to use, it's vital that your public methods represent elements of functionality that you actually want other developers to use.</p>
<p>Public methods should rarely, if ever, be altered. This is because other developers may be relying on your public methods to be consistent, and a change to a public method may break components of their programs.</p>
<p>So, if you can’t change public methods, how can you work on a production application? That’s where <strong>private methods</strong> come in. A private method is a method that is only accessed by the class that it is contained in. It should never be called by outside services. This means that you can alter their behavior, assuming that these changes don’t have a domino effect and alter the public methods that they may be called from.</p>
<p>Usually private methods are placed at the end of the file after all the public methods. To designate private methods, we use the <code>private</code> word above the list of methods. Let’s add a private method to our <code>ApiConnector</code> class:</p>
<p>Notice how we’re calling this method from the inside of the <code>initialize</code> method of the <code>ApiConnector</code> class? If we run this code, it will give the following output:</p>
<pre><code>[Out:]A secret message <span class="hljs-keyword">from</span> the parent <span class="hljs-class"><span class="hljs-keyword">class</span></span>
</code></pre><p>Now child classes have access to methods in the parent class, right? Well, not always. Let’s remove the <code>secret_method</code> method from the <code>initialize</code> method in <code>ApiConnector</code> and try to call it from our <code>SmsConnector</code> child class, as shown here:</p>
<pre><code>[Out:]Traceback (most recent call last):main.rb:<span class="hljs-number">29</span>:<span class="hljs-keyword">in</span> <span class="hljs-string">`&lt;main&gt;': private method `</span>secret_method<span class="hljs-string">' called for #SmsConnector:0x000056188cfe19b0&gt; (NoMethodError)</span>
</code></pre><p>This is because the <code>SmsConnector</code> class only has access to the public methods from the parent class. The private methods are, by their nature, private. This means that they can only be accessed by the class that they are defined in.</p>
<p>So a good rule of thumb is to create private methods when they should not be used outside the class and public methods when they have to be available throughout the application or used by outside services.</p>
<h4 id="heading-wrapping-up">Wrapping up</h4>
<p>I hope you enjoyed this quick tutorial on the fundamental concepts of object-oriented programming in Ruby! We covered creating classes, attribute accessors, instantiation, initialization, inheritance, and private and public methods.</p>
<p>Ruby is a powerful object-oriented language used by popular applications, including our own here at Next Tech. With this foundational knowledge of OOP, you’re well on your way to developing your own Ruby apps!</p>
<p><em>If you’re interested in learning more about programming with Ruby, check out our Introduction to Ruby course <a target="_blank" href="https://c.next.tech/2EyLhYk">here</a>! In this course we cover core programming skills, such as variables, strings, loops, and conditionals, more advanced OOP topics, and error handling.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An overview of how arrays work ]]>
                </title>
                <description>
                    <![CDATA[ By Edison Yap In computer science, there is the concept of a linear data structure, which means that the data are structured in a linear way in which order matters. There are Arrays and Linked Lists, but today I’ll be talking mostly about arrays, and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-arrays-work-the-way-arrays-work-a775bfee519e/</link>
                <guid isPermaLink="false">66c34cd65ced6d98e4bd3314</guid>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 13 Feb 2019 03:05:06 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*IAFX-G9C6sOXI-s6Q0widw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Edison Yap</p>
<p>In computer science, there is the concept of a <strong>linear data structure</strong>, which means that the data are structured in a linear way in which <strong>order matters</strong>. There are <strong>Arrays</strong> and <strong>Linked Lists</strong>, but today I’ll be talking mostly about arrays, and a little about linked lists.</p>
<p>Most object-orientated languages come with <strong>Arrays</strong>, whereas most _f_unctional languages come with <strong>Linked Lists</strong> (see why in another one of my articles, mentioned at the bottom of this article).</p>
<p>There’s a good reason for this differentiation which we will dive into later. For now let’s just have a quick look at the differences between the two data structures. To do this, we’ll need to take a trip down memory lane.</p>
<h3 id="heading-rewind-time">Rewind Time</h3>
<p>Objects and functions and everything that we know about computers, are fundamentally stored in bits and bytes in the computer.</p>
<p>In languages like Java and C, you have to explicitly declare the size of an array beforehand.</p>
<blockquote>
<p><em>Hold up, but Ruby does not do that?</em></p>
</blockquote>
<p>In Ruby, we use <code>Array</code> for our linear data structures. We can add seemingly infinite things into a Ruby array and it would not matter as far as we are concerned.</p>
<p>That’s great isn’t it?! That means arrays are <strong>infinitely</strong> large right? And that Ruby is the superior language? Lucky us!</p>
<p>But not so fast. <em><em>pops your bubble</em></em></p>
<p>There are no <strong>infinite size arrays;</strong> what you see in Ruby is what we call a <strong>Dynamic Array</strong>, and it comes with a cost.</p>
<p>To understand what dynamic arrays are, let’s first take a look at how arrays are represented in memory. Since MRI Ruby (Matz’ Ruby Interpreter) compiles down to C code, we’ll look at how arrays are represented in C.</p>
<h3 id="heading-c-ing-is-believing">C-ing is believing</h3>
<p>We’ll dive into a little bit of C code to help us C a little better… :)</p>
<p>In lower level languages like C, you have to deal with pointers and memory allocation yourself. Even if you have not dealt with C before (d<em>isclaimer — neither have I</em>), you may have C-een one of the most (in)famous examples below:</p>
<p>Let’s break down this bit of code:</p>
<ul>
<li><code>malloc</code> doesn't have any magic meaning behind it, it literally stands for <code>memory allocation</code></li>
<li><code>malloc</code> returns a pointer</li>
<li><code>malloc</code> takes in an argument, which is the size the memory you want the program to allocate for you.</li>
<li><code>100 * sizeof(int)</code> tells the program that we want to store 100 integers, so allocate us 100 * the size of what each integer would occupy.</li>
<li><code>ptr</code>/pointer stores reference to the memory address.</li>
</ul>
<h3 id="heading-timmy-stores-luggage">Timmy stores luggage!</h3>
<p>If the above example did not really make sense, try this analogy. Think of memory allocation as a luggage concierge. It works like this:</p>
<ul>
<li>Timmy goes to the counter, tells the concierge that he has 2 pieces of luggage, about <em>this</em> big, and that that he’d like to store them in the storeroom.</li>
<li>The concierge takes a look at the store room and go “Yes, we’ve got some room at the designated <code>B4</code> area and will allocate that space to store your luggage".</li>
<li>They hand Timmy a <strong>pick-up card</strong> with the designated area on it, <code>B4</code> in our case.</li>
<li>Timmy is happy, goes around doing whatever, and when he wants to pick-up his luggage, he goes back to the counter and shows them his <strong>pick-up card</strong>. “<em>Have you C-een my luggage?</em>”</li>
</ul>
<p>In our example, Timmy’s luggage is the <strong>data</strong>, the <strong>pick-up card is the pointer</strong> (it states where Timmy’s bag is stored). The place that the concierge is storing Timmy’s luggage is the <strong>memory block</strong>, and the counter is the <strong>program</strong>.</p>
<p>By showing the counter (<strong>the program</strong>) Timmy’s card (<strong>pointer/memory address</strong>), Timmy can retrieve his luggage (<strong>data</strong>). Bonus? Because they know <strong>exactly</strong> where Timmy’s bag is stored — <code>B4</code>, this means that they can retrieve all Timmy's luggage relatively quickly!</p>
<p>Also, ever wondered why you access elements in array with <strong>index</strong>, like so?</p>
<p>This is because the array holds the references to the memory block, and the index is telling it the <strong>offset</strong>.</p>
<p>An analogy for that is if I ask you to look for Timmy in a queue of 20 people, you would logically have to ask each of them if they were Timmy. But, if I told you Timmy is the 6th (<strong>index</strong>) from the first person (<strong>your original pointer</strong>), you know exactly where to look.</p>
<p>Retrieving elements in arrays is fast exactly because of this — the program doesn’t have to look through all 100 elements to find what you’re looking for. If you’ve got the index, it just has to add the offset to the original memory address, and the droid that you were looking for will be right there!</p>
<h3 id="heading-what-are-dynamic-arrays-then">What are dynamic arrays then?</h3>
<p>So I’ve told you a little about how arrays are represented in memory, but now it’s time to talk about some cons.</p>
<p>Remember how you have to explicitly declare the amount of memory you need? This means that the array will find a spot that will fit exactly your size. There’s no guarantee that it will be able to fit more than what you have (because the memory block right behind it might be occupied).</p>
<p>Back to our luggage analogy: think of it as if Timmy was to store 2 pieces of luggage, and <code>B4</code>can store exactly 2 pieces of luggage, so they allocate that to Timmy. Now for some reason Timmy wants to store <em>another</em> piece of luggage, but <code>B4</code> can't store 3 pieces, only 2, so what do they do?</p>
<p>They take all of his existing luggage, move it into a new spot that can fit more than 3 pieces, and then store all of them together.</p>
<p>That is an expensive operation but it’s exactly how memory works too!</p>
<p>In Ruby, you don’t have to declare a specific size <em>before hand</em>, but that’s because Ruby handles it for you automagically through dynamic arrays.</p>
<p>What a dynamic array does is that if the array is nearing its full capacity, it’ll automatically declare a new, bigger array and move all existing elements into it, and the old array is then garbage collected. How much bigger? The growth factor is <em>usually</em> 2; double the size of the current array.</p>
<p><strong>In fact, don’t take my word for it</strong>.</p>
<p>Ruby has an <a target="_blank" href="https://ruby-doc.org/core-2.2.0/ObjectSpace.html">ObjectSpace module</a> that allows us to interact with current objects living in memory. We can use this module to take a peek at the memory usage of our dynamic array — sounds exactly like what we want!</p>
<p>I have written a small Ruby script that calculates the growth factor of the dynamic array. Feel free to take a look at it <a target="_blank" href="https://gist.github.com/edisonywh/c61b3ab50359e68454d87b2c13d5d1a8">here</a>, and if you do, you can see that Ruby arrays have a 1.5x growth factor (that is, they make an array that’s 50% bigger on every copy).</p>
<h3 id="heading-i-know-what-arrays-are-what-are-linked-lists">I know what arrays are, what are linked lists?</h3>
<p>Keep in mind that although arrays and linked lists are both considered linear data structures, they have one big difference between them.</p>
<p>Elements in an array are stored literally right next to each other in memory (so we can have index for fast lookups). But nodes in linked lists have no such restriction (which is why there’s no index lookup for linked lists) — each and every item can be stored anywhere on the memory block.</p>
<p>It’s almost as if Timmy’s trying to store 5 pieces of luggage, and the concierge does not have a space and decides to leave them all over the place. Sounds unorganized?</p>
<p>Also if they are stored in different places, how do you know which bags are Timmy’s? <em>Hint: Just keep track of the next node/bag!</em> In our case, the concierge keeps them separately but with a tag on each of them that points to the next bag.</p>
<p>A node in a linked list consists of two parts — the data part and a pointer to the next node. This is how they’re able to maintain the <code>linear</code> part of it -- they still have the concept of order, they just don't have to be stored in order literally!</p>
<p><code>node = [ data | pointer ]</code></p>
<p>For example, given the following example stored in memory:</p>
<p><code>[C | D] [A | B] [B | C] [D | nil]</code></p>
<p>This bits look like it’s out of order — but if I had told you that the first element is <code>A</code>, you would be able to tell me the exact order of the list:</p>
<p><code>list = [A -&gt; B -&gt; C -&gt;</code> D -&gt; nil]</p>
<p>There’s a lot of interesting things that you can do with linked lists which I’m not going to dive into here (also a lot on Big O that I didn’t talk about). But there are already a ton of good articles out there on data structures. If you made it here, I suggest you to read from Ali’s blogpost <a target="_blank" href="https://dev.to/aspittel/thank-u-next-an-introduction-to-linked-lists-4pph">here</a>.</p>
<p><a target="_blank" href="https://dev.to/aspittel/thank-u-next-an-introduction-to-linked-lists-4pph"><strong>thank u, next: an introduction to linked lists</strong></a><br><a target="_blank" href="https://dev.to/aspittel/thank-u-next-an-introduction-to-linked-lists-4pph">_In this post, we are going to be talking about the linked list data structure in the language of "thank u, next" by…_dev.to</a></p>
<p>You can also read more about List/Cons on <a target="_blank" href="https://en.wikipedia.org/wiki/Cons">Wiki here</a>.</p>
<h3 id="heading-closing-note">Closing Note</h3>
<p>I initially wrote this article for a slightly different topic — <a target="_blank" href="https://dev.to/edisonywh/-elixir--why-linked-lists--1e9d">[ Elixir | Why Linked Lists?]</a>, but found it took way too long to explain how arrays work before I was able to explain explore why Elixir uses linked lists. So I have separated them into two articles.</p>
<p>In that article, I talk about why functional languages use linked lists as their linear data structure. Do check it out!</p>
<p><a target="_blank" href="https://dev.to/edisonywh/-elixir--why-linked-lists--1e9d"><strong>[ Elixir | Why Linked Lists? ]</strong></a><br><a target="_blank" href="https://dev.to/edisonywh/-elixir--why-linked-lists--1e9d">_I've always thought data structures are cool, but you know what's cooler? Seeing them in the wild! While going through…_dev.to</a></p>
<h3 id="heading-sources">Sources</h3>
<ol>
<li><a target="_blank" href="https://medium.com/@rebo_dood/ruby-has-a-memory-problem-part-1-7887bbacc579">https://medium.com/@rebo_dood/ruby-has-a-memory-problem-part-1-7887bbacc579</a> — This is where I found out about additional <code>ObjectSpace</code> methods by requiring it</li>
</ol>
<p><em>Originally posted on <a target="_blank" href="https://dev.to/edisonywh/how-arrays-work-the-way-arrays-work-3bpg">dev.to</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Quick Look at Action Text for Rails 6.0 ]]>
                </title>
                <description>
                    <![CDATA[ By Arun Mathew Kurian Rails 6.0 is almost here. The stable version will be released on April 30. The Rails 6.0 beta1 was released on January 15. As Rails releases always are, Rails 6.0 is also action-packed. There are two major frameworks newly intro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/quick-look-at-action-text-in-rails-6-0-12a8f9f7597f/</link>
                <guid isPermaLink="false">66c35d2b56e6b06442afd853</guid>
                
                    <category>
                        <![CDATA[ Rails 6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Action Text ]]>
                    </category>
                
                    <category>
                        <![CDATA[ rich text editor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby on Rails ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 29 Jan 2019 09:51:36 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*0-LAOoPHs63XCSd3VDJ2Eg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Arun Mathew Kurian</p>
<p><a target="_blank" href="https://weblog.rubyonrails.org/">Rails 6.0</a> is almost here. The stable version will be released on April 30. The Rails 6.0 beta1 was released on January 15. As Rails releases always are, Rails 6.0 is also action-packed. There are two major frameworks newly introduced, <a target="_blank" href="https://weblog.rubyonrails.org/2018/12/13/introducing-action-mailbox-for-rails-6/">Action Mailbox</a> and <a target="_blank" href="https://weblog.rubyonrails.org/2018/10/3/introducing-action-text-for-rails-6/">Action Text</a>. In this post, let's take a quick look at Action Text by using it in a small app.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*0-LAOoPHs63XCSd3VDJ2Eg.png" alt="Image" width="800" height="301" loading="lazy">
<em>courtesy:wikipedia</em></p>
<h4 id="heading-action-text">Action Text</h4>
<p>Action Text allows us to bring rich text content and editing to Rails. This means we can perform operations like formatting text, embedding images, formatting links, adding lists and other editor-like feature to a text field.</p>
<p>This is done by including the <a target="_blank" href="https://github.com/basecamp/trix">Trix editor</a> into the framework. The RichText content generated by the Trix editor is saved in its own RichText model that’s associated with any existing Active Record model in the application. All embedded images or other attachments are automatically stored using <a target="_blank" href="https://edgeguides.rubyonrails.org/active_storage_overview.html">Active Storage.</a></p>
<p>Let us start building our Rails app which will be a blogger app. The app is created in Rails 6.0, so the ruby version must be &gt;2.5.</p>
<p>In the terminal type</p>
<pre><code>rails <span class="hljs-keyword">new</span> blog --edge
</code></pre><p>The -- edge flag fetches the latest rails version or edge version of the rails.</p>
<p>Action Text expects web packer and ActiveStorage to be installed. The active storage is already present in the Rails app. So we need</p>
<pre><code>gem “image_processing”, “~&gt; <span class="hljs-number">1.2</span>” #uncomment <span class="hljs-keyword">from</span> Gemfilegem ‘webpacker’
</code></pre><p>in the gem file.</p>
<p>Now run</p>
<pre><code>bundle install.
</code></pre><p>Next, we need to create a config/webpacker.yml:</p>
<pre><code>bundle exec rails webpacker:install
</code></pre><p>Now let us start our Rails Server.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*YXa6Y6mfxGa2E2m5hnwuug.png" alt="Image" width="800" height="449" loading="lazy"></p>
<p>Great, let’s quickly build our app. The app will have only one model Article.</p>
<p>Let us create a controller for articles:</p>
<pre><code>rails g controller Articles index <span class="hljs-keyword">new</span> create show edit update destroy — no-helper — no-test-frameworks
</code></pre><p>And then configure our routes:</p>
<pre><code>Rails.application.routes.draw <span class="hljs-keyword">do</span> resources :articlesend
</code></pre><p>Next, we need to create our model. Our Articles model will have two fields: they are <strong>title</strong> and <strong>text</strong>. text must be the field that accepts Rich Text Format. So in the migration, we need to add only the title field. The text field will be handled by ActionText.</p>
<p>Let’s generate the model</p>
<pre><code>rails g model Articles title:string — no-test-framework
</code></pre><p>and run the migrations:</p>
<pre><code>rails db:migrate
</code></pre><p>Now let us add ActionText part. For that first run</p>
<pre><code>rails action_text:install
</code></pre><p>This will add all the dependencies required by Action Text. Most notably, this will add a new file <strong>javascript/packs/application.js</strong> and two action-storage migrations.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*1nE9nc8I6E2jC-EnEy394A.png" alt="Image" width="800" height="465" loading="lazy"></p>
<p>Run the migrations again using</p>
<pre><code>rails db:migrate
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*AzLR2ezD1weUwRXHKghCTQ.png" alt="Image" width="718" height="208" loading="lazy"></p>
<p>Now we can add the text part of our model. Go to <strong>app/models/article.rb</strong> and add the following line</p>
<p><code>has_rich_text **:text**</code></p>
<p>text is the field name we are providing. It can be anything like body or content etc.</p>
<p>Now our model becomes</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Article</span> &lt; <span class="hljs-title">ApplicationRecord</span> <span class="hljs-title">has_rich_text</span> :<span class="hljs-title">textend</span></span>
</code></pre><p>Before we build our form, let’s create our controller logic for the creation of articles:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ArticlesController</span> &lt; <span class="hljs-title">ApplicationController</span>  <span class="hljs-title">def</span> <span class="hljs-title">create</span>   @<span class="hljs-title">article</span> </span>= Article.new(article_params)   @article.save   redirect_to @article end
</code></pre><pre><code> private def article_params   params.require(:article).permit(:title, :text) end
</code></pre><pre><code>end
</code></pre><p>We can now create the form for the blog. In <strong>app/views/articles/new.rb</strong> add the following form code:</p>
<pre><code>&lt;%= form_with scope: :article, <span class="hljs-attr">url</span>: articles_path, <span class="hljs-attr">local</span>: <span class="hljs-literal">true</span> <span class="hljs-keyword">do</span> |form| %&gt;
</code></pre><pre><code>&lt;p&gt;    &lt;%= form.label :title %&gt;<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">form.text_field</span> <span class="hljs-attr">:title</span> %&gt;</span>  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">form.label</span> <span class="hljs-attr">:text</span> %&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">form.rich_text_area</span> <span class="hljs-attr">:text</span> %&gt;</span>  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>   <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">form.submit</span> %&gt;</span>  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">%</span> <span class="hljs-attr">end</span> %&gt;</span></span>
</code></pre><p>Notice that for text field we are using <strong>form.rich_text_area</strong> which is provided by Action Text.</p>
<p>Let us render our page:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*zpL22oO9exBtJqvJ75dFPw.png" alt="Image" width="800" height="449" loading="lazy"></p>
<p>Awesome!!</p>
<p>We now have an awesome text editor for creating our article.</p>
<p>Before we start playing with the editor, let’s quickly implement the <strong>show</strong> functionality of the blog, so that we can see the articles we have created.</p>
<p>In <strong>app/controllers/articles_controller.rb</strong> add the following function:</p>
<pre><code> def show   @article = Article.find(params[:id]) end
</code></pre><p>Also, we need to create a view for this.</p>
<p>Create the file <strong>app/views/articles/show.html.erb</strong> and add the following code:</p>
<pre><code>&lt;p&gt;Article Title:<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">%=</span> @<span class="hljs-attr">article.title</span> %&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span></span>&lt;<span class="hljs-regexp">/p&gt;&lt;p&gt;Article Text:&lt;strong&gt;&lt;%= @article.text %&gt;&lt;/</span>strong&gt;&lt;/p&gt;
</code></pre><pre><code>&lt;%= link_to ‘Create <span class="hljs-keyword">new</span>’,new_article_path %&gt;
</code></pre><p>That's it. Our app is done. Now let's check the various features available in the text editor provided by ActionText.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*_tH1tezWuI8khKwrieWjZw.png" alt="Image" width="800" height="449" loading="lazy"></p>
<p>We can see that ActionText provides almost all the functionalities of a normal rich text-editor like formatting the text as bold, italic, adding strike-throughs, quotes, links, dragging and dropping images, etc.</p>
<p>After saving this, we can see the saved post from the show page.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*QD3WpW9992Wzo9a1yPyHgw.png" alt="Image" width="800" height="449" loading="lazy"></p>
<p>Great!</p>
<p>This is a very small example that displays the potential of ActionText. Hope it was helpful. Do give it a try.</p>
<p>A vast majority of web apps deal with rich content in some way. So I believe this new feature of Rails can make the lives of many developers easier.</p>
<p>Kudos to DHH and all the awesome people behind this.</p>
<p><a target="_blank" href="https://github.com/amkurian/Rails-6.0_action_text_demo">https://github.com/amkurian/Rails-6.0_action_text_demo</a></p>
<p>Some Useful Links:</p>
<p><a target="_blank" href="https://edgeguides.rubyonrails.org/action_text_overview.html"><strong>Action Text Overview - Ruby on Rails Guides</strong></a><br><a target="_blank" href="https://edgeguides.rubyonrails.org/action_text_overview.html">_Action Text OverviewThis guide provides you with all you need to get started in handling rich text content.After…_edgeguides.rubyonrails.org</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to calculate Binary Tree height with the recursive method ]]>
                </title>
                <description>
                    <![CDATA[ Previously I wrote about an algorithm for finding out the height of a binary tree using iteration. Though that method gets the job done (in 7 steps no less), the same can be accomplished in a much simpler way. In my opinion, one of the most powerful ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-calculate-binary-tree-height-with-the-recursive-method-aafc461f2201/</link>
                <guid isPermaLink="false">66bb524c074d8d7b12eae37c</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Recursion ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ry Vee ]]>
                </dc:creator>
                <pubDate>Mon, 07 Jan 2019 23:49:21 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*ci3-dY6FOCFu2UeqtzJ73A.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Previously I wrote about an algorithm for finding out the height of a binary tree <a target="_blank" href="https://medium.freecodecamp.org/how-to-calculate-a-binary-trees-height-using-array-iteration-in-ruby-63551c6c65fe">using iteration</a>. Though that method gets the job done (in 7 steps no less), the same can be accomplished in a much simpler way.</p>
<p>In my opinion, one of the most powerful programming techniques is recursion. For readers new to programming — it is simply a function or method calling itself. To make the introduction simpler we have a method below that calls another method:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_method</span><span class="hljs-params">(name)</span></span>       (R1)
  inner_method + name
<span class="hljs-keyword">end</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_method</span>             <span class="hljs-params">(R2)</span></span>
  <span class="hljs-string">"Hello "</span>
<span class="hljs-keyword">end</span>
print outer_method(<span class="hljs-string">"Steve"</span>) -&gt; <span class="hljs-comment">#"Hello Steve"</span>
</code></pre>
<p>In the above method <code>outer_method</code>, which takes in a string as argument, calls <code>inner_method</code>, which simply returns the string <code>“Hello “</code> inside it. Recursion is similar in that, say in this case, <code>outer_method</code> simply calls itself:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_method</span><span class="hljs-params">(name)</span></span>              (R3)
  outer_method(<span class="hljs-string">"hello "</span>) + name
<span class="hljs-keyword">end</span> (R3)
</code></pre>
<p>One caveat, though, with code <code>R3</code> above — it will run until the computer complains that resources are not enough to keep processing the method. It’s like running an infinite loop except that infinite loops don’t necessarily raise exceptions. The reason for this is that code <code>R3</code> doesn’t have a ‘terminal state’ or a point where it doesn’t ‘recurse’ anymore.</p>
<p>We can solve this by including a terminal state:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_method</span><span class="hljs-params">(name)</span></span>                 (R4)
  <span class="hljs-keyword">return</span> name <span class="hljs-keyword">if</span> name == <span class="hljs-string">"hello "</span>
  outer_method(<span class="hljs-string">"hello "</span>) + name
<span class="hljs-keyword">end</span>
</code></pre>
<p>The first line inside the method definition simply states that if the argument <code>name</code> is equal to <code>‘hello’</code> then simply return <code>name</code>. That will then ignore any line after it. Therefore in the second line, the code <code>outer_method(“hello “)</code> will simply give the string “hello “ to be added to whatever name is in the main argument. So the same <code>print outer_method(“Steve”)</code> will result in the output <code>“hello Steve”</code> as well.</p>
<p>OK then, that may not be the best example for describing recursion (as the recursive version in this case doesn’t have that much advantage over the non-recursive one). But working on the binary tree height problem, we will see that recursion is so much simpler to understand and faster to run.</p>
<p>For this discussion let me put again the same example as I showed in the previous article:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*tsVyCA_zXrAh3LqTF4LHxw.png" alt="Image" width="727" height="337" loading="lazy">
<em>Figure 1: Simple binary tree</em></p>
<p>which we can represent as the following array:</p>
<pre><code class="lang-ruby">tree = [<span class="hljs-number">1</span>, <span class="hljs-number">7</span>, <span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">5</span>, <span class="hljs-number">11</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>] (T<span class="hljs-number">0</span>)
</code></pre>
<p>The indices of the left and right children of any sub tree can be determined as follows:</p>
<pre><code class="lang-ruby">left child of tree[i] is at index <span class="hljs-number">2</span>*i + <span class="hljs-number">1</span> (T1)
right child of tree[i] is at index <span class="hljs-number">2</span>*i + <span class="hljs-number">2</span> (T2)
</code></pre>
<p>If you’re puzzled about how the figure above became the array following it, I’ll direct you to read the <a target="_blank" href="https://medium.freecodecamp.org/how-to-calculate-a-binary-trees-height-using-array-iteration-in-ruby-63551c6c65fe">previous article</a> on the iterative method for clarification.</p>
<p>And again the formula for calculating the height of a binary tree, as well as the heights of any of its sub trees, is:</p>
<pre><code class="lang-ruby">height = <span class="hljs-number">1</span> + max of(left_child_height, right_child_height) (T3)
</code></pre>
<p>Now with these we can outline the steps to develop a recursive program.</p>
<p><strong>Step 0:</strong> Set default values — To make the initial method call simple, I always like setting default values for the arguments that will change during each recursive call. Since we will repetitively compute heights, our indices will always change.</p>
<p>For instance, to find the height of the root’s (<code>tree[0]</code>) left child we will need to call the method on that left child (whose index is at <code>2*(0) + 1</code>). Therefore, our method definition will be:</p>
<pre><code class="lang-rb"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">tree_height_recursive</span><span class="hljs-params">(tree_array,i=<span class="hljs-number">0</span>)</span></span> (S<span class="hljs-number">0</span>.<span class="hljs-number">1</span>)
</code></pre>
<p>to indicate that for the initial call we are calling it on the root element. This will simply allow us to call <code>tree_height_recursive</code> by inputting only the tree_array. However, this also means, as we will see in the simulation afterwards, we can find the height of any sub tree by simply including its index as the second argument in the method call.</p>
<p><strong>Step 1:</strong> Find terminal state — At which point do we simply return a value and not do any further recursive calls? In our binary tree problem, the terminal state is at:</p>
<pre><code class="lang-rb"><span class="hljs-keyword">return</span> <span class="hljs-number">0</span> <span class="hljs-keyword">if</span> tree[i].<span class="hljs-literal">nil</span> <span class="hljs-keyword">or</span> tree[i] == <span class="hljs-number">0</span> (S1.<span class="hljs-number">1</span>)
</code></pre>
<p>It simply says that if the element at index <code>i</code> does not exist or if its value is 0 then simply return 0. Logically, a non-existing sub tree will not have any height.</p>
<p><strong>Step 2:</strong> Find the height of the left child — this is where the magic of recursion starts to benefit us. We don’t need any fancy code. No more declaring another array to hold the height of each element. No more multiple variable definitions for height indices and the heights themselves, just:</p>
<pre><code class="lang-rb">right_child_height = tree_height_recursive(tree_array, <span class="hljs-number">2</span>*i + <span class="hljs-number">2</span>)
</code></pre>
<p>We simply pass the index of the left child as second argument. Can you see why?</p>
<p>We do the same for finding the right child’s height next.</p>
<p><strong>Step 3:</strong> Find the height of right child — Likewise, we simply do a recursive call to our method but passing the index of the right child as second argument:</p>
<pre><code class="lang-rb">right_child_height = tree_height_recursive(tree_array, <span class="hljs-number">2</span>*i + <span class="hljs-number">2</span>)
</code></pre>
<p>Now that we have the heights of the left and right children, we can now compute the total height.</p>
<p><strong>Step 4:</strong> Calculate and return total height — As code <code>T3</code> states, we just add 1 and the height of whichever is taller between the left and right children.</p>
<pre><code class="lang-rb">total_height = <span class="hljs-number">1</span> + [left_child_height, right_child_height].max (S4.<span class="hljs-number">1</span>)
</code></pre>
<p>Since <code>S.4</code> will be the last statement in our method, then the evaluated <code>total_height</code> will be returned. Remember that if the conditions in <code>S1.1</code> hold true (our terminal state) then none of Steps 2–4 will run and the method will simply return 0.</p>
<p>The full method below:</p>
<p>Comparing this to the <a target="_blank" href="https://medium.freecodecamp.org/how-to-calculate-a-binary-trees-height-using-array-iteration-in-ruby-63551c6c65fe">iterative method</a>, the recursive version took 3 fewer steps and 4 fewer variable definitions. The code also (excluding empty spaces and comments) is 7 lines fewer. On top of it, the recursive code will run 2x faster (using the <code>benchmark</code> built-in Ruby module). This is a big advantage if we’re running the method on binary trees hundreds of levels tall.</p>
<p>Now let’s do the same simulation as we did before. For the tree at <code>T0</code> we run the recursive method:</p>
<pre><code>tree = [<span class="hljs-number">1</span>, <span class="hljs-number">7</span>, <span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">5</span>, <span class="hljs-number">11</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>]
</code></pre><pre><code class="lang-rb">puts tree_height_recursive(tree_array)-&gt; <span class="hljs-comment">#should give us 4</span>
</code></pre>
<p>Note that since we have a default <code>i=0</code> in our method definition we don’t need to specify the index here because we are finding the height of the whole tree. To make this simulation more intuitive we shall create an imaginary array called <code>call_stack</code> where push every call to <code>tree_height_recursive</code>.</p>
<p>So then when we call the method the first time (the main call), we store it in a temporary variable <code>ht_0</code> and push it to <code>call_stack</code>:</p>
<pre><code>ht_0 = height <span class="hljs-keyword">of</span> tree[<span class="hljs-number">0</span>] = tree_height_recursive(tree_array,i=<span class="hljs-number">0</span>)
</code></pre><pre><code class="lang-rb">call_stack = [ht_<span class="hljs-number">0</span>]
</code></pre>
<p>We then run Step 1:</p>
<pre><code class="lang-rb">tree[<span class="hljs-number">0</span>].<span class="hljs-literal">nil</span>? -&gt; <span class="hljs-comment">#falsetree[0] == 0 -&gt; #false, it is 2</span>
</code></pre>
<p>Since this results in <code>false</code>, we go ahead to Step 2:</p>
<pre><code>since i= <span class="hljs-number">0</span>, then <span class="hljs-number">2</span>*i + <span class="hljs-number">1</span> = <span class="hljs-number">2</span>*<span class="hljs-number">0</span> + <span class="hljs-number">1</span> = <span class="hljs-number">1</span>:
</code></pre><pre><code class="lang-rb">left_child_height = tree_height_recursive(tree_array,<span class="hljs-number">1</span>)
</code></pre>
<p>Since we cannot readily determine this height so then we push it again to <code>call_stack</code>:</p>
<pre><code>ht_1 = left_child_height = tree_height_recursive(tree_array,<span class="hljs-number">1</span>)
</code></pre><pre><code>call_stack = [ht_0,ht_1]
</code></pre><p>Then upon doing Step 3:</p>
<pre><code class="lang-rb">ht_2 = right_child_height = left_child_height = tree_height_recursive(tree_array,)
</code></pre>
<pre><code class="lang-rb">call_stack = [ht<span class="hljs-number">0</span>,ht1,ht2]
</code></pre>
<p>We cannot proceed to Step 4 until all the items in <code>call_stack</code> have been evaluated by our program and popped off from <code>call_stack</code> (which should happen for every time each height has been evaluated).</p>
<p>So we will also do the same for each of the succeeding heights. For instance, to compute <code>ht1</code> we know that we have to compute for its own left and right children’s heights too. So that means the method will be called for them too. So as not to prolong this article, the reader is invited to try this on paper.</p>
<p>Ultimately, the method will be called recursively with <code>i = 14</code> as second argument. Thus, at this point, <code>call_stack</code> will be:</p>
<pre><code class="lang-rb">call_stack = [ht<span class="hljs-number">0</span>,ht1,ht2,ht3,ht4,ht5,ht6,ht7,ht8,ht9,ht1<span class="hljs-number">0</span>,ht11,ht12,ht13,ht14]
</code></pre>
<p>Now we will evaluate each. Note that from <code>tree[7]</code> up to <code>tree[14]</code> the elements don’t have any children. So we can simply evaluate their heights as 1 or 0 (depending on whether <code>tree[i]</code> is 0 or not (where <code>i ≥ 7</code>):</p>
<pre><code>ht14 = <span class="hljs-number">0</span>
</code></pre><pre><code>ht13 = <span class="hljs-number">1</span>
</code></pre><pre><code>ht12 = <span class="hljs-number">0</span>
</code></pre><pre><code>ht11 = <span class="hljs-number">0</span>
</code></pre><pre><code>ht10 = <span class="hljs-number">1</span>
</code></pre><pre><code>ht9 = <span class="hljs-number">1</span>
</code></pre><pre><code>ht8 = <span class="hljs-number">1</span>
</code></pre><pre><code>ht7 = <span class="hljs-number">1</span>
</code></pre><p>Again, when these heights are evaluated we simply pop them off successively from <code>call_stack.</code> After which, <code>call_stack</code> will appear as follows:</p>
<pre><code class="lang-rb">call_stack = [ht<span class="hljs-number">0</span>, ht1, ht2, ht3, ht4, ht5, ht6]
</code></pre>
<p>Now, to evaluate <code>ht6</code> we must remember that it is the call to <code>tree_height_recursive(tree_array, 6)</code>. Inside this call we also call on the method to compute for the heights of the left and right children of <code>tree[6]</code>. These we previously already evaluated as <code>ht13</code> and <code>ht14</code>. So then:</p>
<pre><code class="lang-rb">ht6 = <span class="hljs-number">1</span> + [ht13, ht14].max = <span class="hljs-number">1</span> + [<span class="hljs-number">1</span>,<span class="hljs-number">0</span>] = <span class="hljs-number">1</span> + <span class="hljs-number">1</span> = <span class="hljs-number">2</span>
</code></pre>
<p>So we now evaluate <code>ht5</code>, which is the height of <code>tree[5]</code>. We know the heights of its children are <code>ht11</code> and <code>ht12</code></p>
<pre><code class="lang-rb">ht5 = <span class="hljs-number">1</span> + [ht11,ht12].max = <span class="hljs-number">1</span> + [<span class="hljs-number">0</span>,<span class="hljs-number">0</span>].max = <span class="hljs-number">1</span> + <span class="hljs-number">0</span> = <span class="hljs-number">1</span>
</code></pre>
<p>Doing the same for <code>ht4</code> to <code>h1</code> (again the reader is invited to do the confirmation on paper):</p>
<pre><code>ht4 = <span class="hljs-number">1</span> + [ht9,ht10].max = <span class="hljs-number">1</span> + [<span class="hljs-number">1</span>,<span class="hljs-number">1</span>].max = <span class="hljs-number">1</span> + <span class="hljs-number">1</span> = <span class="hljs-number">2</span>
</code></pre><pre><code>ht3 = <span class="hljs-number">1</span> + [ht7, ht8].max = <span class="hljs-number">1</span> + [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>].max = <span class="hljs-number">1</span> + <span class="hljs-number">1</span> = <span class="hljs-number">2</span>
</code></pre><pre><code>ht2 = <span class="hljs-number">1</span> + [ht5, ht6].max = <span class="hljs-number">1</span> + [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>].max = <span class="hljs-number">1</span> + <span class="hljs-number">2</span> = <span class="hljs-number">3</span>
</code></pre><pre><code class="lang-rb">ht1 = <span class="hljs-number">1</span> + [ht3, ht4].max = <span class="hljs-number">1</span> + [<span class="hljs-number">2</span>,<span class="hljs-number">2</span>].max = <span class="hljs-number">1</span> + <span class="hljs-number">3</span> = <span class="hljs-number">3</span>
</code></pre>
<p>Again, we pop out each height from <code>call_stack</code> as we evaluate it so after evaluating <code>ht1</code> the <code>call_stack</code> appears as follows:</p>
<pre><code class="lang-rb">call_stack = [ht<span class="hljs-number">0</span>]
</code></pre>
<p>Now evaluating <code>ht0</code> is returning to the main call to <code>tree_height_recursive</code>, so this is the remaining Step 4:</p>
<pre><code class="lang-rb">ht<span class="hljs-number">0</span> = <span class="hljs-number">1</span> + [ht1, ht2].max = <span class="hljs-number">1</span> + [<span class="hljs-number">3</span>, <span class="hljs-number">3</span>].max = <span class="hljs-number">1</span> + <span class="hljs-number">3</span> = <span class="hljs-number">4</span>ortotal_height = <span class="hljs-number">1</span> + [left_child_height, right_child_height].max
</code></pre>
<p>Which will return <code>4</code> as the result of the main method call.</p>
<p>As I keep mentioning, doing this on paper whether during the algorithm formulation or during simulation will help a lot in understanding it. This same method can also be used to determine the height of any of the sub trees inside the <code>tree_array</code>, for instance to determine only the height of the tree’s left child:</p>
<pre><code class="lang-rb">puts tree_height_recursive(tree_array, <span class="hljs-number">1</span>) -&gt; <span class="hljs-comment">#will print out 3</span>
</code></pre>
<p>Or any of the lower sub trees:</p>
<pre><code class="lang-rb">puts tree_height_recursive(tree_array, <span class="hljs-number">3</span>) -&gt; <span class="hljs-comment">#will print out 2</span>
</code></pre>
<h4 id="heading-wrapping-up">Wrapping up</h4>
<p>The key takeaway in creating a recursive algorithm, in my perspective, is setting the terminal state. Again, this is the scenario wherein the main method will not have to do any recursive call to itself. Without this, the method will just keep calling itself until the computer blows up (hyperbolically speaking…). When we have the terminal state we can easily set the arguments for the recursive calls and know that our method will safely return the value we expect.</p>
<p>Finally, working on algorithms challenge our minds to think. As software engineers, or even engineers in general, our main task is to solve problems. We, therefore, need to develop our critical thinking skills.</p>
<p>If for a problem, our first option is always ‘google it’ and copy/paste other people’s code without fully understanding the problem and the copied solution, then we are defeating ourselves.</p>
<p>So my suggestion is always have pen and paper ready and not immediately type code when faced with an algorithm challenge. Simulate the problem for simple inputs then come up with the code after you determine the steps (like I outlined them above).</p>
<p><strong>Follow me</strong> on <a target="_blank" href="https://twitter.com/coachryanv"><strong>Twitter</strong></a> | <a target="_blank" href="https://github.com/rvvergara"><strong>Github</strong></a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
