<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Randall Reed on Medium]]></title>
        <description><![CDATA[Stories by Randall Reed on Medium]]></description>
        <link>https://medium.com/@randallreedjr?source=rss-62e3adfb5b22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dWbzLLqWjgPD4KZuCkEgWw.png</url>
            <title>Stories by Randall Reed on Medium</title>
            <link>https://medium.com/@randallreedjr?source=rss-62e3adfb5b22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:03:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@randallreedjr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Easily Manage Multiple Git Profiles]]></title>
            <link>https://randallreedjr.medium.com/how-to-easily-manage-multiple-git-profiles-418c9ad6dd0c?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/418c9ad6dd0c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 15:48:05 GMT</pubDate>
            <atom:updated>2023-07-22T19:22:24.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A pile of lego heads" src="https://cdn-images-1.medium.com/max/1024/1*eGpp_qICw2daGI8W4gyyxw.jpeg" /><figcaption>Keeping work life separate from personal life can sometimes be overwhelming — Photo by <a href="https://unsplash.com/@jan_huber?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jan Huber</a> on <a href="https://unsplash.com/photos/AF6N3WRsyk4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Managing multiple git profiles can be challenging, but it doesn’t have to be.</em></p><h3>Too Many git Profiles</h3><p>Once upon a time, during a consulting engagement, I found myself juggling three different git profiles:</p><ol><li>My personal account (r@g.com)</li><li>My work account (r@c.com)</li><li>My client account (r@x.com)</li></ol><p>I would occasionally commit code under each of the three accounts — client work under the “client” account, internal consultancy work under the “work” account, and open source work under my “personal” account. Often, I would realize too late that I had written a commit (or several) under the wrong account, and I would have to reset my branch and rewrite those commits with the correct account.</p><h4>An elegant solution</h4><p>Out of this frustration, I came up with two useful strategies:</p><ol><li>I started displaying the current git username in my terminal prompt and created a simple command to display the user context</li></ol><pre># .zshrc<br><br># Find and set git username var<br>function git_user_name()<br>{<br>  user=$(git config user.username 2&gt; /dev/null)<br>  if [[ $user == &quot;&quot; ]];<br>  then<br>    :<br>  else<br>    echo &#39;&#39;$user&#39;&#39;<br>  fi<br>}<br># Include git username in prompt<br>prompt=&#39;working as %F{green}$(git_user_name)&#39;$&#39;\n&#39;&#39;☆%f &#39;<br><br># Use `me` to show local user, git user, and current active ssh key<br>alias me=&#39;echo &quot;local: $(whoami)&quot;; echo &quot;git: $(git config user.email)&quot;; echo &quot;ssh: $(ssh-add -l)&quot;&#39;</pre><p>2. I created <a href="https://github.com/randallreedjr/git_swap">git swap</a>, to easily manage git profiles</p><pre>$ me<br>git: r@g.com<br><br>$ git swap work<br>$ me<br>git: r@c.com<br><br>$ git swap client<br>$ me<br>git: r@x.com</pre><h3>git swap</h3><p>So what is “git swap” you’re asking? It is a command line utility that can be used to easily swap between git profiles! Built with Ruby and distributed as a Homebrew formula, it generates a custom git command, swap, used to easily update your git name, username, email, and active ssh key.</p><p>During setup, configuration is stored in ~/.gitswap, in YAML format. Note that you can use whatever naming convention you like for your profiles (personal/work, opensource/professional, etc). Mine looks something like this:</p><pre>personal:<br>  username: randallreedjr<br>  email: r@g.com<br>  name: Randall Reed, Jr.<br>  ssh: ~/.ssh/id_rsa<br>work:<br>  username: c-randall<br>  email: r@c.com<br>  name: Randy Reed<br>  ssh: ~/.ssh/work_rsa<br>client:<br>  username: x-randall<br>  email: r@x.com<br>  name: Randall Reed<br>  ssh: ~/.ssh/client_rsa</pre><p>Additionally, if you protect your SSH keys with a passphrase (as you should!), git swap will automatically include --apple-use-keychain to apply your saved passphrase. That way, you don’t have to manually type it in every time you switch contexts!</p><p>If this is a challenge you face, I encourage you to give git swap a try! I am the author and sole maintainer, and gladly welcome any feedback you may have.</p><p>For more information about creating your own custom git commands, check out <a href="https://gitbetter.substack.com/p/automate-repetitive-tasks-with-custom">this excellent tutorial</a> which includes several useful examples!</p><h4>P.S. — Why not call it git switch?</h4><p><em>Great question! git swap was originally created as </em><a href="https://github.com/randallreedjr/git_switch"><em>git switch</em></a>, <em>but then git released their own </em><a href="https://git-scm.com/docs/git-switch"><em>switch</em></a><em> command and broke my custom one. How dare they!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=418c9ad6dd0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with git remotes on Heroku]]></title>
            <link>https://randallreedjr.medium.com/working-with-git-remotes-on-heroku-65e46cd05fee?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/65e46cd05fee</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 16:56:44 GMT</pubDate>
            <atom:updated>2020-06-05T16:56:44.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Generally, you will add a git remote for your Heroku app during the Heroku app creation process, i.e. heroku create. However, if you are working on an existing app and want to add git remotes to enable manual deploys, the following commands may be useful.</p><p><em>Note: This article began as a </em><a href="https://gist.github.com/randallreedjr/aa89e069371d07371882eea2df15fb4d"><em>GitHub Gist</em></a><em> and grew from there with helpful input from other GitHub users, as cited below.</em></p><h3>Adding a new remote</h3><h4>Add a remote for your Staging app and deploy</h4><p>Note that on Heroku, you must always use master as the destination branch on the remote. If you want to deploy a different branch, you can use the syntax local_branch:destination_branch seen below (in this example, we push the local staging branch to the master branch on Heroku.</p><pre>$ git remote add staging https://git.heroku.com/staging-app.git<br>$ git push staging staging:master</pre><p>In some cases, your local branch may be missing some commits that were already deployed to Heroku, resulting in an error. If you are very sure you want to proceed, add the --force (-f) flag.</p><pre>$ git push staging staging:master -f</pre><h4>Add a remote for your Production app and deploy</h4><p>By convention, the remote name “heroku” is typically used for the production application.</p><pre>$ git remote add heroku https://git.heroku.com/app.git<br>$ git push heroku master</pre><h4>Add a remote via Heroku CLI</h4><p>As <a href="https://gist.github.com/randallreedjr/aa89e069371d07371882eea2df15fb4d#gistcomment-3079752">@voke</a> points out, you can alternatively use a <a href="https://devcenter.heroku.com/articles/git#creating-a-heroku-remote">Heroku CLI command</a> to add your remote. However, it looks like this will always use the default remote name heroku for the remote. If you would like to use a different name for your remote, see the &quot;Rename a remote&quot; section below.</p><pre>$ heroku git:remote -a staging-app</pre><p>Edit: Thanks to <a href="https://gist.github.com/randallreedjr/aa89e069371d07371882eea2df15fb4d#gistcomment-3141611">@nruth</a> for pointing out you can supply a remote name to this command with the -r flag.</p><pre>$ heroku git:remote -a staging-app -r staging</pre><h4>Add a remote using the SSH protocol</h4><p>As <a href="https://gist.github.com/randallreedjr/aa89e069371d07371882eea2df15fb4d#gistcomment-2784952">@Saworieza</a> points out, all of the examples above use the https protocol for connecting to the remotes, but it is also possible to connect via ssh.</p><pre>$ git remote add staging git@heroku.com:staging-app.git<br>$ git remote add heroku git@heroku.com:app.git</pre><h3>Other useful commands</h3><h4>List your git remotes</h4><p>The -v is the flag for “verbose” and includes the remote URL in addition to the remote name.</p><pre>$ git remote -v</pre><h4>Rename a remote</h4><pre>$ git remote rename heroku staging</pre><h4>Change a remote URL or protocol</h4><p>If you have already created https remotes and want to switch them to use ssh, the following command can be used. This command can also be used to change the target URL without changing the protocol.</p><pre>$ git remote set-url staging git@heroku.com:staging-app.git<br>$ git remote set-url heroku <a href="https://git.heroku.com/production-app.git">https://git.heroku.com/production-app.git</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65e46cd05fee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Math Behind an Innovative Code Solution]]></title>
            <link>https://randallreedjr.medium.com/exploring-the-math-behind-an-innovative-code-solution-40009370e311?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/40009370e311</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 14:43:18 GMT</pubDate>
            <atom:updated>2018-12-03T14:43:18.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*rkE6o0LBcIeqqYFJ-NspLQ.png" /></figure><p>Consider the following coding challenge:</p><blockquote>Return the sum of all multiples of 3 or 5 that are below a number N, where N is an input parameter to the function</blockquote><p>When writing software, there is no single correct answer. The author of the article below explores six different solutions to the aforementioned problem, working through the thought process behind iterating towards a final solution.</p><p><a href="https://medium.freecodecamp.com/what-i-learned-from-writing-six-functions-that-all-did-the-same-thing-b38fd48f0d55">What I learned from writing six functions that all did the same thing</a></p><p>This article is definitely an interesting read, but what interested me the most was the function at the end, one which far surpassed the others in term of performance.</p><p>Here is the function:</p><pre>function multMath(n) {<br>  var threes = Math.floor(--n / 3);<br>  var fives = Math.floor(n / 5);<br>  var fifteens = Math.floor(n / 15);<br>  <br>  return (3 * threes * (threes + 1) + 5 * fives * (fives + 1) - 15 * fifteens * (fifteens + 1)) / 2;<br>}</pre><pre>module.exports = multMath;</pre><p><em>In the original article, the function was named</em> multSilgarth, <em>presumably after the </em><a href="https://www.freecodecamp.org/forum/u/silgarth"><em>user</em></a><em> who wrote it. I have renamed the function here to minimize confusion.</em></p><p>Let’s break down what this function is doing</p><ol><li>Find the number multiples of 3 below the specified number</li><li>Find the number multiples of 5 below the specified number</li><li>Find the number of multiples of 15 below the specified number</li><li>Perform some <strong>magic math</strong> and return the result</li></ol><blockquote>Math is cool!</blockquote><p>When I read this article, I recognized a familiar formula, one which I believe may not be common knowledge to the average person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*p4kL1jF1ymZWhGRPlkL6cA.gif" /><figcaption>created using <a href="https://www.codecogs.com/latex/eqneditor.php">https://www.codecogs.com/latex/eqneditor.php</a></figcaption></figure><p>This is the equation for the <a href="https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF">sum of natural numbers</a>. Say one wanted to know how many pips (or dots) are on a 6-sided die; one would need to add up 1+2+3+4+5+6. This equation gives us a shortcut: n * (n + 1) / 2. For n = 6 (the upper limit of the series to be summed):</p><pre>n*(n+1)/2<br>=&gt; 6*(6+1)/2<br>==&gt; 6*7/2<br>===&gt; 42/2<br>====&gt; 21</pre><p>The insight of this solution, and why it was so efficient, is the way it uses math to avoid loops. Whereas using a for or while loop is an intuitive approach that would occur first to most programmers, using a formula to optimize summation is not necessarily self-evident. This mathematical approach reduces the complexity of the solution from O(n) to O(1)!</p><p>We don’t have a lot of control structures in programming (mostly if/else branches and for/while loops), so we tend to think of solutions to problems in those terms. I think this specific example is a good counterpoint to the notion that one does not need to be good at math when learning to code, as discussed in the article below. <strong>While most of the coding I have done requires little to no math, or basic math,</strong> math can sometimes help with optimizations.</p><p><a href="https://www.theatlantic.com/technology/archive/2015/09/you-dont-have-to-be-good-at-math-to-learn-to-code/403342/">You Don&#39;t Have to Be Good at Math to Learn to Code</a></p><h3>Let’s break down the code for anything that might be unfamiliar</h3><p>Here’s the original function again:</p><pre>function multMath(n) {<br>  var threes = Math.floor(--n / 3);<br>  var fives = Math.floor(n / 5);<br>  var fifteens = Math.floor(n / 15);<br>  <br>  return (3 * threes * (threes + 1) + 5 * fives * (fives + 1) - 15 * fifteens * (fifteens + 1)) / 2;<br>}</pre><pre>module.exports = multMath;</pre><h4>(x * (x + 1)) / 2</h4><p>The first important part to understand is that there is a formula to determine the sum of any series of natural numbers up to and including n: (n * (n + 1)) / 2. There are many <a href="http://www.9math.com/book/sum-first-n-natural-numbers">good proofs</a>, but here’s an explanation that makes the most sense to me.</p><p>Consider summing the digits 1–10. For each number in the sequence, we can pair it with a later number in the sequence to produce the same value.</p><pre>0 + 10 =&gt; 10<br>1 + 9  =&gt; 10<br>2 + 8  =&gt; 10<br>3 + 7  =&gt; 10<br>4 + 6  =&gt; 10<br>5</pre><pre>n = 10, n / 2 = 5 groups</pre><p>In this case, we have 5 groups of 10’s, plus a single 5 left over (the midpoint in the sequence). Because numbers from the earlier part of the sequence pair off with numbers in the later part of the sequence, we will always have n / 2 groups for even-numbered sequences (e.g. n = 10) OR (n + 1) / 2 groups for odd-numbered sequences (e.g. n = 5).</p><pre>0 + 5  =&gt; 5<br>1 + 4  =&gt; 5<br>2 + 3  =&gt; 5</pre><pre>n = 5, (n + 1) / 2 = 3 groups</pre><p>Additionally, in the case of even-numbered sequences, the midpoint number will be left out of any group, so we have an additional n/2 term.</p><pre>Odd sequence: (n + 1) / 2 groups of n<br>Even sequence: (n / 2) groups of n, + (n / 2)</pre><p>Now, groups of n is the same things as saying * n, so we can rewrite this as</p><pre>Odd sequence: (n + 1) / 2 * n<br>Even sequence: (n / 2) * n + (n / 2)</pre><p>Finally, simplifying the terms yields:</p><pre>(n + 1) / 2 * n<br>=&gt; (n * (n + 1)) / 2</pre><pre>(n / 2) * n + (n / 2)<br>=&gt; (n^2 / 2) + (n / 2) <br>==&gt; (n^2 + n) / 2 <br>===&gt; (n * (n + 1)) / 2</pre><p><em>Note that the final equation for both sequences is</em> (n * (n + 1)) / 2</p><h4>function sumToN(n)</h4><p>We could then write a simple helper function:</p><pre>function sumToN(n) {<br>  return n * (n + 1) / 2;<br>}</pre><p><em>Remember that multiplication and division are commutative, so it doesn’t matter in which order we perform them.</em></p><p>Plugging that function into the original code above would yield a more semantic version:</p><pre>function multMath(N) {<br>  var threes = Math.floor(--n / 3);<br>  var fives = Math.floor(n / 5);<br>  var fifteens = Math.floor(n / 15);<br>  <br>  return (3 * sumToN(threes) + 5 * sumToN(fives) - 15 * sumToN(fifteens);<br>}</pre><pre>function sumToN(n) {<br>  return n * (n + 1) / 2;<br>end</pre><pre>module.exports = multMath;</pre><h4>3 * sumToN(threes)</h4><p>The next part requires us to abandon how we might usually check for multiples of three or five (iterating over an integer range and using modulo, %).</p><pre>// A traditional approach<br>function sumMultiplesOfThree(n) {<br>  let i = 0, sum = 0;<br>  while(i &lt; n) {<br>    if(i % 3 == 0) {<br>      sum += i<br>    }<br>    i++;<br>  }<br>  return sum;<br>}</pre><p>Consider solving this problem for N = 30</p><pre>multiples of 3: 3, 6, 9, 12, 15, 18, 21, 24, 27<br>multiples of 5: 5, 10, 15, 20, 25</pre><p><em>Since the problem specifies </em>less than N, <em>we have to exclude the number itself.</em></p><p>Unfortunately, the formula we derived above for the sum of natural numbers does not allow us to sum <strong>non-sequential</strong> sets of integers. However, we can see that the sets of multiples can be reduced by dividing by their factor:</p><pre>multiples of 3: 3 * [1, 2, 3, 4, 5, 6, 7, 8, 9]<br>multiples of 5: 5 * [1, 2, 3, 4, 5]</pre><p>Great! Now we have two sequences of natural numbers again! Substituting our helper function once more yields</p><pre>sum of multiples of 3: 3 * sumToN(9)<br>sum of multiples of 5: 5 * sumToN(5)</pre><p>Okay, but how do we know what number to pass to the sumToN function? Asking “How many multiples of three are there less than or equal to 30?” is the same as performing division; 30 / 3 = 10 is the same as saying “There are 10 multiples of 3 less than or equal to 30” because there is a sequence of 10 integers that you pass through by adding 3 to itself until you arrive at 30.</p><p>Now, since we want to sum the multiples “less than” the number n, we need to insure we never include n itself, which can be accomplished by (n — 1) / 3. Furthermore, to avoid decimal numbers in cases where n — 1 is not divisible by 3 (e.g. 29 / 3 = 9.66666666...), we use the mathematical function floor, which just means “always round down to the next lowest integer.”</p><p>Putting this all together, we see that the number of multiples of three less than n is</p><pre>Math.floor((n - 1) / 3);</pre><p>Generalizing to any divisor, we can create another helper function:</p><pre>function numberOfMultiplesLessThanN(divisor, n) {<br>  Math.floor((n - 1) / divisor);<br>}</pre><p>Then, substituting what we’ve just learned into the original function gives us our final version of the function:</p><pre>function multMath(n) {<br>  var threes = numberOfMultiplesLessThanN(3, n);<br>  var fives = numberOfMultiplesLessThanN(5, n);<br>  var fifteens = numberOfMultiplesLessThanN(15, n);<br>  <br>  return (3 * sumToN(threes) + 5 * sumToN(fives) - 15 * sumToN(fifteens);<br>}</pre><pre>function sumToN(n) {<br>  return n * (n + 1) / 2<br>end</pre><pre>function numberOfMultiplesLessThanN(divisor, n) {<br>  Math.floor((n - 1) / divisor);<br>}</pre><pre>module.exports = multMath;</pre><p><em>Of course this could be generalized further to accept both divisors as additional arguments to </em>multMath<em>, or even an array of any number of divisors! That is left as an exercise for the reader.</em></p><h4>15 * sumToN(fifteens)</h4><p>There’s just two more pieces left to discuss! First, why do we care about fifteen? As you probably noticed above, our sets of multiples of three and multiples of five are not mutually exclusive</p><pre>multiples of 3: 3, 6, 9, 12, 15, 18, 21, 24, 27<br>multiples of 5: 5, 10, 15, 20, 25</pre><pre>multiples of 3 AND 5: 15</pre><p>There is one number that is in both lists — 15. Any number that is both a multiple of 3 and a multiple of 5 will be <strong>double counted</strong>. Conveniently, we can also say that all of these numbers will be multiples of 15 (if a number is divisible by two integers, it is also divisible by the product of those integers). So subtracting out the sum of the multiples of 15 will remove these duplicates.</p><h4>--n</h4><p>Lastly, there is the matter of —-n. In our version of the function, we are using a helper function for the number of multiples, so we do not use this approach. However, in the original version, we see this</p><pre>var threes = Math.floor(--n / 3);<br>var fives = Math.floor(n / 5);<br>var fifteen = Math.floor(n / 15);</pre><pre>// This is equivalent to<br>var threes = Math.floor((n - 1) / 3);<br>var fives = Math.floor((n - 1) / 5);<br>var fifteen = Math.floor((n - 1) / 15);</pre><p>-- is the decrement operator, so --n is equivalent to n -= 1 or n = n — 1, with one <a href="https://stackoverflow.com/questions/32562795/what-is-the-difference-between-n-and-n">important caveat</a>: --n mutates the value of n before it is used in whatever expression is surrounding it, where as n-- mutates the value of n after using it in the current expression.</p><pre>n = 2<br>--n * 2<br>=&gt; 2<br>n<br>=&gt; 1</pre><pre>n = 2<br>n-- * 2<br>=&gt; 4<br>n<br>=&gt; 1</pre><p>Although a minor optimization, using —-n only does the subtraction once by mutating the variable in place.</p><h3>Conclusion</h3><p>In closing, most programmers will very rarely come across a problem that requires advanced or esoteric math to solve. But the more math you know, the easier it will be for you to spot these opportunities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40009370e311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby’s String#delete and Boolean Algebra]]></title>
            <link>https://medium.com/defmethod-works/rubys-string-delete-and-boolean-algebra-3c737579609b?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c737579609b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[boolean-algebra]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 15:05:13 GMT</pubDate>
            <atom:updated>2018-04-10T15:05:37.711Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How can learning about the String#delete method in Ruby help us understand Boolean Algebra?</em></p><h4>It starts with a misuse of gsub</h4><p>I cannot tell you how many times have I written code like</p><pre>&#39;abc-de&#39;.gsub(&#39;-&#39;,&#39;&#39;)</pre><p>when I could have just written</p><pre>&#39;abc-de&#39;.delete(&#39;-&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Twp6sGJY1oQ02fEG12MkAQ.jpeg" /><figcaption>facepalm</figcaption></figure><p>Fortunately, <a href="http://stackoverflow.com/a/7540789/1951290">Stack Overflow</a> was there to educate me. Not only is delete more semantic and concise than gsub for removing a single character, it gets even better with more complex deletions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*W4Wl1CWi_4JqDDIHdpSi6w.gif" /></figure><h3>Delete with Multiple Characters</h3><p>Imagine that you are working with a long string, maybe one containing the alphabet.</p><pre>alphabet = &#39;abcdefghijklmnopqrstuvwxyz&#39;</pre><p>If you wanted to remove all of the vowels, starting with what we’ve seen from delete so far, you could do something atrocious like:</p><pre>alphabet.delete(&#39;a&#39;).delete(&#39;e&#39;).delete(&#39;i&#39;).delete(&#39;o&#39;).delete(&#39;u&#39;)<br># =&gt; &#39;bcdfghjklmnpqrstvwxyz&#39;</pre><p>Fortunately, the developers of Ruby provide a much simpler approach for this use case. Instead of chaining all these method calls together, you can pass all of the characters at once, and delete will remove any matches.</p><pre>alphabet.delete(&#39;aeiou&#39;)<br># =&gt; &#39;bcdfghjklmnpqrstvwxyz&#39;</pre><p>When executing alphabet.delete(&#39;aeiou&#39;), we are not deleting the string &#39;aeiou&#39; from alphabet; that string does not exist as a substring of alphabet. Instead, we are deleting any element from the set of letters {a,e,i,o,u}.</p><p><em>Consequently, if you </em><strong><em>did</em></strong><em> want to delete a substring from </em>alphabet<em>, e.g. </em>‘lmnop’<em>, I would recommend using </em><a href="https://ruby-doc.org/core-2.5.0/String.html#method-i-slice-21">slice!</a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*W4Wl1CWi_4JqDDIHdpSi6w.gif" /></figure><h3>Delete with Multiple Parameters</h3><p>A feature that makes delete even cooler is how it handles multiple parameters. Working with the same alphabet string, imagine you now want to remove all of the letters that satisfy <strong>both</strong> of the following criteria:</p><ol><li>Is a vowel</li><li>Is in the first quartile of the alphabet (i.e. a-g)</li></ol><p>delete is perfect for this! While delete treats a single argument string as a <strong>set</strong> of characters, when supplied with multiple argument strings, delete will remove the <strong>intersection</strong> of those sets.</p><p><em>Remember </em><a href="https://en.wikipedia.org/wiki/Algebra_of_sets#The_fundamental_laws_of_set_algebra"><em>an intersection </em>(∩)<em> is like AND, whereas a union </em>(⋃) <em>is like OR</em></a>; <em>more on this later</em></p><p>First, let’s take a look at delete handling each of our criteria independently.</p><pre>vowels = &#39;aeiou&#39;<br>first_quartile = &#39;abcdefg&#39;</pre><pre>alphabet.delete(vowels)<br># =&gt; &#39;bcdfghjklmnpqrstvwxyz&#39;<br>alphabet.delete(first_quartile)<br># =&gt; &#39;hijklmnopqrstuvwxyz&#39;</pre><p>Now let’s see what happens when we supply both strings as arguments to delete.</p><pre>alphabet.delete(vowels, first_quartile)<br># =&gt; &#39;bcdfghijklmnopqrstuvwxyz&#39;</pre><p>The only letters deleted from alphabet were ‘a’ and ‘e’, because they were the only letters that appeared in <strong>all</strong> of the strings passed as parameters. That is equivalent to the <strong>intersection</strong> of the sets of characters represented by our two argument strings.</p><pre>{a,e,i,o,u} ∩ {a,b,c,d,e,f,g} = {a,e}</pre><p>Interestingly, the result of using delete with both arguments is the same as the <strong>union</strong> of the results of using delete with each of the arguments independently, once sorted.</p><pre>{b,c,d,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z} = {b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z} ⋃ {h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}</pre><p>Expressed another way, deleting the intersection of vowels and first_quartile is equal to the union of deleting vowels and deleting first_quartile.</p><pre># Call split so we can use Array&#39;s intersection (&amp;) and union (|) operators</pre><pre>intersection = alphabet.delete(<br>  (<br>    vowels.split(&#39;&#39;) &amp; <br>    first_quartile.split(&#39;&#39;)<br>  ).join<br>)<br># =&gt; &quot;bcdfghijklmnopqrstuvwxyz&quot;</pre><pre>union = (<br>  alphabet.delete(vowels).split(&#39;&#39;) |     <br>  alphabet.delete(first_quartile).split(&#39;&#39;)<br>).sort.join<br># =&gt; &quot;bcdfghijklmnopqrstuvwxyz&quot;</pre><pre>intersection == union<br># =&gt; true</pre><p><em>.sort is necessary since union concatenates the two arrays</em></p><p>I think that code got really confusing really fast. But if we replace alphabet.delete with !, and remove the array methods for simplicity, we are left with:</p><pre>!(vowels &amp;&amp; first_quartile) == !vowels || !first_quartile</pre><p>Simplified to the general case, that would look like</p><pre>!(A &amp;&amp; B) == !A || !B</pre><p>That’s pretty neat! And it makes a lot of sense if we think about it from a Boolean Algebra perspective.</p><p><em>For more about </em>delete<em>, check out the </em><a href="https://ruby-doc.org/core-2.5.0/Array.html#method-i-delete"><em>documentation</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*W4Wl1CWi_4JqDDIHdpSi6w.gif" /></figure><h3>Boolean Algebra</h3><p>If you’ve been writing code for any time at all, you are probably familiar with the boolean — a data type that can have either a true or false value (sometimes represented as 1 or 0, respectively). <a href="https://en.wikipedia.org/wiki/Boolean_algebra">Boolean Algebra</a>, then, is the branch of algebra dealing with booleans. It is fundamental to understanding the construction of logical conditions. The properties of Boolean Algebra — its operations, identities, and laws — are often reminiscent of those in arithmetic.</p><blockquote>Boolean Algebra is the branch of algebra in which the values of the variables are the truth values ‘<em>true’</em> and ‘<em>false’</em>, usually denoted 1 and 0 respectively</blockquote><p>We are going to talk about a few boolean operations, focusing on the operators AND, OR, and NOT. Here is a glossary of symbols, each of which you might encounter depending on the source. The “Style” is not actual nomenclature, but rather my way of referring to the area of study where you are most likely to encounter each group of symbols.</p><pre>+-------+-----+-----+-----+<br>| Style | AND | OR  | NOT |<br>+-------+-----+-----+-----+<br>| Set   | A∩B | A⋃B |  Ā  | <br>| Code  | A&amp;B | A|B | !A  |<br>| Math  | A·B | A+B | ~A  |<br>| Logic | A∧B | A∨B | ¬A  |<br>|       |     |     |  A&#39; |<br>+-------+-----+-----+-----+</pre><p><em>Note: In code the logical AND (&amp;) and OR (|) operators are often doubled (&amp;&amp;, ||) to differentiate from </em><a href="https://en.wikipedia.org/wiki/Bitwise_operation#Bitwise_operators"><em>bitwise operators</em></a><em>.</em></p><p>These three primary operations are analogous to <a href="https://en.wikipedia.org/wiki/Intersection_(set_theory)">Intersection</a> (AND), <a href="https://en.wikipedia.org/wiki/Union_(set_theory)">Union</a> (OR), and <a href="https://en.wikipedia.org/wiki/Complement_(set_theory)">Complement</a> (NOT).</p><p>Let’s see an example. If I say “my car is <strong>red</strong> (R) and <strong>fast</strong> (F)”, is that true? We can determine the veracity of the statement as a whole with a truth table, a table that lists all possible values for the inputs (R, F) and the resulting output (R &amp; F).</p><pre>+-------++-------+<br>| R | F || R &amp; F |<br>+---+---++-------+<br>| 0 | 0 ||   0   | // not red, not fast -&gt; not red and fast<br>| 0 | 1 ||   0   | // not red, fast -&gt; not red and fast<br>| 1 | 0 ||   0   | // red, not fast -&gt; not red and fast<br>| 1 | 1 ||   1   | // red, fast -&gt; red and fast<br>+---+---++-------+</pre><p>My car is only “red and fast” if it is both red and fast. So far, this just sounds like common sense. But something else to notice is that, if you look at my car and see it is blue, you know my car is not “red and fast” without even seeing how fast it is. In coding, this is called “short-circuiting,” meaning that if any part of an AND condition is false, the entire condition is false and the rest of the condition does not need to be evaluated.</p><pre>+-------++-------+<br>| R | F || R &amp; F |<br>+---+---++-------+<br>| 0 | x ||   0   | // not red, unknown fast -&gt; not red and fast<br>| x | 0 ||   0   | // unknown red, not fast -&gt; not red and fast<br>| 1 | 1 ||   1   | // red, fast -&gt; red and fast<br>+---+---++-------+</pre><p>On the other hand, what if I said “my car is red <strong>or</strong> fast.”</p><pre>+-------++-------+<br>| R | F || R | F |<br>+---+---++-------+<br>| 0 | 0 ||   0   | // not red, not fast -&gt; not red or fast<br>| 0 | 1 ||   1   | // not red, fast -&gt; red or fast<br>| 1 | 0 ||   1   | // red, not fast -&gt; red or fast<br>| 1 | 1 ||   1   | // red, fast -&gt; red or fast<br>+---+---++-------+</pre><p>Now, as long as my car is red, it is “red or fast,” regardless of the speed. Again, we can short-circuit the evaluation of this statement, because if any part of an OR condition is true, the entire condition is true and the rest of the condition does not need to be evaluated.</p><pre>+-------++-------+<br>| R | F || R | F |<br>+---+---++-------+<br>| 0 | 0 ||   0   | // not red, not fast -&gt; not red or fast<br>| x | 1 ||   1   | // unknown red, fast -&gt; red or fast<br>| 1 | x ||   1   | // red, unknown fast -&gt; red or fast<br>+---+---++-------+</pre><p>More formally, these properties are codified in the <a href="https://en.wikipedia.org/wiki/Boolean_algebra#Monotone_laws">Identity and Annihilator Laws</a>.</p><pre>Identity for ∧: 𝓍 ∧ 1 = 𝓍<br>Identity for ∨: 𝓍 ∨ 0 = 𝓍</pre><pre>Annihilator for ∧: 𝓍 ∧ 0 = 0<br>Annihilator for ∨: 𝓍 ∨ 1 = 1</pre><p>Knowing the four Identity and Annihilator laws will get you through most of the logic you’ll ever need for coding. However, with Ruby, which provides convenient logical complements such as if and unless, select and reject, or any? and none?, I think it helps to understand my favorite pair of laws of Boolean Algebra: De Morgan’s Laws.</p><h4>De Morgan’s Laws</h4><p><a href="https://en.wikipedia.org/wiki/De_Morgan&#39;s_laws">De Morgan’s Laws</a> are “a pair of transformation rules…[that] allow the expression of <a href="https://en.wikipedia.org/wiki/Logical_conjunction">conjunctions</a> and <a href="https://en.wikipedia.org/wiki/Logical_disjunction">disjunctions</a> purely in terms of each other via <a href="https://en.wikipedia.org/wiki/Logical_negation">negation</a>,” as follows.</p><pre>Negation of a disjunction: ¬(A ∨ B) = (¬A) ∧ (¬B)<br>Negation of a conjunction: ¬(A ∧ B) = (¬A) ∨ (¬B)</pre><p>Here it is again “in English”:</p><blockquote>the complement of the union of two sets is the same as the intersection of their complements; and the complement of the intersection of two sets is the same as the union of their complements.</blockquote><p>To translate into Ruby:</p><ul><li>When you read ‘complement’ think ! (NOT)</li><li>When you read ‘union’ think || (OR)</li><li>When you read ‘intersection’ think &amp;&amp; (AND)</li></ul><p>Which gives us:</p><pre>!(A || B) == !A &amp;&amp; !B<br>!(A &amp;&amp; B) == !A || !B</pre><p>Just like we saw above!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*W4Wl1CWi_4JqDDIHdpSi6w.gif" /></figure><h3>Deleting Without Delete</h3><p>To see De Morgan’s Laws in action, we can try a homegrown implementation of delete using the Enumerable methods select and reject.</p><pre>alphabet.split(&#39;&#39;).select {|c| !vowels.include?(c) || !first_quartile.include?(c) }.join<br># retain the letters that are either NOT in vowels OR NOT in first_quartile</pre><pre>alphabet.split(&#39;&#39;).reject {|c| vowels.include?(c) &amp;&amp; first_quartile.include?(c)}.join<br># discard the letters that are in BOTH vowels AND first_quartile</pre><p><em>Since the String class does not include the Enumerable module, we first use </em>split<em> to convert the alphabet to an array of characters; </em>join<em> is used to reassemble the remaining characters back into a string.</em></p><p>With select, we want to keep any letter that is <strong>either</strong> NOT in vowels or NOT in first_quartile; whereas with reject, we want to discard any letter that IS in <strong>both</strong> of the strings. Because select and reject are complements of each other, their conditions should be logical inverses of each other as well. This can easily be demonstrated with a trivial exercise.</p><pre>arr = [1,2,3,4,5]<br>arr.reject {|a| a.odd?} == arr.select {|a| !a.odd?}<br># =&gt; true</pre><p>Going back to our alphabet example, we should be able to demonstrate</p><pre># !(reject_condition) == select_condition</pre><pre>!(vowels.include?(c) &amp;&amp; first_quartile.include?(c)) == !vowels.include?(c) || !first_quartile.include?(c)</pre><p>If we replace vowels.include?(c) with A and first_quartile.include?(c) with B, we get</p><pre>!(A &amp;&amp; B) == !A || !B</pre><p><em>Et voila! </em>Is this starting to look familiar yet?</p><p>Keeping De Morgan’s Laws in mind allows you to switch freely between select and reject, or other logical complements. You may find this helps you convert your logical expressions into something more intuitive. Is it easier for you to wrap your head around one code snippet over the other? (For me, reject makes a lot more sense in this case.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*W4Wl1CWi_4JqDDIHdpSi6w.gif" /></figure><h3>More Truth Tables and Karnaugh Maps</h3><p>As with the “fast and red car” example, we can use a truth table for our alphabet expression. In this case, to be consistent with what we’ll see later, we are using slightly different notation; !A || !B becomes A&#39; + B&#39; and !(A &amp;&amp; B) becomes &#39;(A·B) or simply &#39;(AB).</p><pre>+-------++---------+-------+----+<br>| A | B || A&#39; + B&#39; | &#39;(AB) | AB |<br>+---+---++---------+-------+----+<br>| 0 | 0 ||    1    |   1   | 0  |<br>| 0 | 1 ||    1    |   1   | 0  |<br>| 1 | 0 ||    1    |   1   | 0  |<br>| 1 | 1 ||    0    |   0   | 1  |<br>+---+---++---------+-------+----+</pre><p>The truth table confirms what we already demonstrated with boolean algebra — that the expressions A&#39; + B&#39; and &#39;(AB) are equivalent, and both are the inverse of AB.</p><p>Finally, we can use a tool called a <a href="https://en.wikipedia.org/wiki/Karnaugh_map">Karnaugh Map</a>, or K-map, to approach this problem from a slightly different angle. A K-map is useful for mapping a set of requirements to the desired logical outcomes, to derive a logical expression satisfying the requirements. Furthermore, if you already have a logical expression, K-maps can sometimes help you find a simpler expression that yields the same results. It is akin to a truth table, but laid out in a sort of grid.</p><pre>+---------------+<br>|       |   A   |<br>+       +---+---+<br>|       | 0 | 1 | &lt;- Input values for A<br>+---------------+<br>| B | 0 |   |   | &lt;- Results (to be determined)<br>|   | 1 |   |   | <br>+---+---+---+---+<br>      ^<br>Input values for B</pre><p>So once again, let’s say that we want to keep the letters in the string alphabet that are either not in vowels (A) or not in first_quartile (B). The K-map is filled out by evaluating our various inputs and filling in the corresponding outputs.</p><ul><li>If A is false (0) and B is false (0), the letter is not in vowels and not in first_quartile, and therefore should be kept in our string (1).</li></ul><pre>+---------------+<br>|       |   A   |<br>+       +---+---+<br>|       | 0 | 1 | &lt;- Input values for A<br>+---------------+<br>| B | 0 | 1 |   | &lt;- Results<br>|   | 1 |   |   | <br>+---+---+---+---+<br>      ^<br>Input values for B</pre><ul><li>If A is true (1) and B is false (0), the letter is in vowels but not in first_quartile, and should be kept in our string (1).</li></ul><pre>+---------------+<br>|       |   A   |<br>+       +---+---+<br>|       | 0 | 1 | &lt;- Input values for A<br>+---------------+<br>| B | 0 | 1 | 1 | &lt;- Results<br>|   | 1 |   |   | <br>+---+---+---+---+<br>      ^<br>Input values for B</pre><ul><li>If A is false (0) and B is true (1), the letter is not in vowels but is in first_quartile, and should be kept in our string (1).</li></ul><pre>+---------------+<br>|       |   A   |<br>+       +---+---+<br>|       | 0 | 1 | &lt;- Input values for A<br>+---------------+<br>| B | 0 | 1 | 1 | &lt;- Results<br>|   | 1 | 1 |   | <br>+---+---+---+---+<br>      ^<br>Input values for B</pre><ul><li>Finally, if A is true (1) and B is true (1), the letter is in vowels and is also in first_quartile, and thus should not be kept in our string (0).</li></ul><pre>+---------------+<br>|       |   A   |<br>+       +---+---+<br>|       | 0 | 1 | &lt;- Input values for A<br>+---------------+<br>| B | 0 | 1 | 1 | &lt;- Results<br>|   | 1 | 1 | 0 | <br>+---+---+---+---+<br>      ^<br>Input values for B</pre><p>Now that the K-map has been filled out, the goal is to find the <strong>minimum</strong> number of <strong>maximum </strong>(largest)<strong> </strong>groupings that cover all true outcomes, as illustrated below (sometimes this is <strong>much</strong> simpler than <a href="https://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm">others</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*DxhD9dD0lXtuOHzxYK7iQA.png" /><figcaption>a Karnaugh Map for A’ + B’</figcaption></figure><p>The groupings represent logical expressions.</p><ul><li>The red rectangle in the image above corresponds to A = 0, or A’</li><li>The blue rectangle in the image corresponds to B = 0, or B’.</li><li>Even though both rectangles cover the condition A=0, B=0, this duplication is preferable as it yields a simpler logical expression.</li></ul><p>To combine both predicates, we use a union, yielding A’ + B’ (hence K=A&#39;+B&#39; in the image); the complement is also listed, K’=AB. Once again, this is consistent with what we saw before!</p><pre>!A || !B == !(A &amp;&amp; B)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*W4Wl1CWi_4JqDDIHdpSi6w.gif" /></figure><p><em>Boolean algebra is just one of the many topics engineers at </em><a href="https://medium.com/defmethod-works"><em>Def Method</em></a><em> chat about in our free time. If you’re facing a technical challenge, we’d love to </em><a href="https://www.defmethod.com/services/"><em>work with you</em></a><em>. And </em><a href="https://www.defmethod.com/were-hiring"><em>we’re hiring</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c737579609b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/defmethod-works/rubys-string-delete-and-boolean-algebra-3c737579609b">Ruby’s String#delete and Boolean Algebra</a> was originally published in <a href="https://medium.com/defmethod-works">Def Method</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nine Interesting Tidbits About Dates In Ruby]]></title>
            <link>https://medium.com/defmethod-works/nine-interesting-tidbits-about-dates-in-ruby-62fec30fcf01?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/62fec30fcf01</guid>
            <category><![CDATA[date]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 18:55:25 GMT</pubDate>
            <atom:updated>2018-03-19T19:20:43.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grwOX564MY4GdWpVh5zJpQ.jpeg" /><figcaption>source: <a href="https://www.pexels.com/photo/laptop-calendar-and-books-908298/">https://www.pexels.com/photo/laptop-calendar-and-books-908298/</a></figcaption></figure><p><em>Note: This article sat in my drafts folder for a long time. I recently had to look up how to determine the weekday-ness of a date, so I decided to finally give this a publish.</em></p><p><strong>1. To use </strong><a href="https://ruby-doc.org/stdlib-2.5.0/libdoc/date/rdoc/Date.html"><strong>Date</strong></a><strong> objects in Ruby, you must require the ‘date’ library.</strong></p><pre># ruby-2.5.0<br>&gt; Date.new<br>NameError (uninitialized constant Date<br>Did you mean?  Data)<br>&gt; require &#39;date&#39;<br> =&gt; true<br>&gt; Date.new<br> =&gt; #&lt;Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)&gt;</pre><p>Unsurprisingly, Date is already included in Rails.</p><p><strong>2. </strong>Date.new<strong> takes arguments in the order year, month, day — the same order as </strong><a href="https://en.wikipedia.org/wiki/ISO_8601"><strong>ISO 8601</strong></a><strong>. This format is also sometimes referred to as </strong><a href="https://en.wikipedia.org/wiki/Date_format_by_country"><strong>Big Endian</strong></a><strong>.</strong></p><pre># ruby-2.5.0<br>&gt; Date.new(2018, 3, 19)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;</pre><p>You can use -1 to refer to the last day of a month.</p><pre>#ruby-2.5.0<br>&gt; Date.new(2018, 3, -1)<br> =&gt; #&lt;Date: 2018-03-31 ((2458209j,0s,0n),+0s,2299161j)&gt;</pre><p>There are also some shortcut methods, like Date.today. However, you’ll need to include ActiveSupport if you want access to Date.yesterday or Date.tomorrow.</p><pre># ruby-2.5.0<br>&gt; today = Date.today<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;<br>&gt; Date.tomorrow<br>NoMethodError (undefined method `tomorrow&#39; for Date:Class)</pre><p><strong>3. Attempting to create a date that does not exist will raise an exception.</strong></p><pre># ruby-2.5.0<br>&gt; Date.new(2018, 2, 31)<br>ArgumentError (invalid date)</pre><p>If concerned about possible invalid date parameters, you can first check them using Date.valid_date?.</p><pre># ruby-2.5.0<br>&gt; Date.valid_date?(2018, 2, 31)<br> =&gt; false<br>Date.valid_date?(2018, 2, 28)<br> =&gt; true</pre><p><strong>4. You can access the various parts of the date with methods like </strong>.year<strong>, </strong>.month<strong>, and </strong>.day<strong>.</strong></p><pre># ruby-2.5.0<br>&gt; today.year<br> =&gt; 2018<br>&gt; today.month<br> =&gt; 3<br>&gt; today.day<br> =&gt; 19</pre><p><strong>5. There are boolean methods to determine the day of the week.</strong></p><pre># ruby-2.5.0<br>&gt; today.monday?<br> =&gt; true<br>&gt; today.friday?<br> =&gt; false</pre><p>You can use .wday to get a zero-based number for the day of the week (with 0 being Sunday and 6 being Saturday). Alternatively, .cwday yields a one-based number (with 1 being Monday and 7 being Sunday).</p><pre># ruby-2.5.0<br>&gt; sunday = Date.new(2018, 3, 18)<br> =&gt; #&lt;Date: 2018-03-18 ((2458196j,0s,0n),+0s,2299161j)&gt;<br>&gt; sunday.wday<br> =&gt; 0<br>&gt; sunday.cwday<br> =&gt; 7</pre><p><strong>6. Date objects respond to the </strong>upto<strong> or </strong>downto<strong> messages, so you can iterate over a date range.</strong></p><pre># ruby-2.5.0<br>&gt; sunday.upto(today) { |date| puts date }<br>2018-03-18<br>2018-03-19</pre><p><strong>7. A Date can be created from a string using </strong>parse. <strong>Impressively, it is compatible with a variety of formats.</strong></p><pre># ruby-2.5.0<br>&gt; Date.parse(&#39;2018-03-19&#39;)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;<br>&gt; Date.parse(&#39;20180319&#39;)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;<br>&gt; Date.parse(&#39;19th Mar 2018&#39;)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;<br>&gt; Date.parse(&#39;Monday March 19, 2018&#39;)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;</pre><p>If you want to be more explicit about your date format, use strptime and pass a <a href="https://ruby-doc.org/stdlib-2.5.0/libdoc/date/rdoc/Date.html#method-c-strptime"><strong>date format string</strong></a>. The default format is ‘yyyy-m-dd.’</p><pre># ruby-2.5.0<br>&gt; Date.strptime(&#39;2018-03-19&#39;)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;<br>&gt; Date.strptime(&#39;2018/03/19&#39;)<br>ArgumentError (invalid date)<br>&gt; Date.strptime(&#39;March 19, 2018&#39;, &#39;%B %d, %Y&#39;)<br> =&gt; #&lt;Date: 2018-03-19 ((2458197j,0s,0n),+0s,2299161j)&gt;</pre><p><strong>8. </strong>strftime<strong> reverses this operation, returning a string representation of a date (I always read this as <em>str</em>ing <em>f</em>rom <em>time</em>). The same </strong><a href="http://ruby-doc.org/core-2.5.0/Time.html#method-i-strftime"><strong>formatting rules</strong></a><strong> apply. By default, </strong>to_s<strong> formats the date in the same ISO 8601 format we’ve come to expect, as does </strong>iso8601<strong>.</strong></p><pre># ruby-2.5.0<br>&gt; today.to_s<br> =&gt; &quot;2018-03-19&quot;<br>&gt; today.iso8601<br> =&gt; &quot;2018-03-19&quot;<br>&gt; today.strftime(&#39;%Y-%m-%d&#39;)<br> =&gt; &quot;2018-03-19&quot;<br>&gt; today.strftime(&#39;%B %d, %Y&#39;)<br> =&gt; &quot;March 19, 2018&quot;</pre><p>However, for the special case of converting a date to a weekday, consider using DAYNAMES. The constant DAYNAMES is an array of the names of the days of the week, and, I would argue, more semantic than strftime in this case.</p><pre># ruby-2.5.0<br>&gt; Date::DAYNAMES<br> =&gt; [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;]<br>&gt; Date::DAYNAMES[today.wday]<br> =&gt; &quot;Monday&quot;<br>&gt; today.strftime(&#39;%A&#39;)<br> =&gt; &quot;Monday&quot;</pre><p>Performance wise, DAYNAMES appears to be a clear winner.</p><pre># ruby-2.5.0<br>&gt; require &#39;benchmark&#39;<br> =&gt; true<br>&gt; puts Benchmark.measure { 10000.times { Date::DAYNAMES[today.wday] } }<br> 0.001394   0.000007   0.001401 (  0.001395)<br>&gt; puts Benchmark.measure { 10000.times { today.strftime(&#39;%A&#39;) } }<br> 0.003813   0.000030   0.003843 (  0.003839)</pre><p><em>(You can learn more about the Benchmark module </em><a href="https://ruby-doc.org/stdlib-2.5.0/libdoc/benchmark/rdoc/Benchmark.html"><em>here</em></a><em>.)</em></p><p><strong>9. Basic arithmetic can be used with date objects, though </strong>next/succ<strong> and </strong>prev<strong> are more semantic ways to accomplish the same goal.</strong></p><pre># ruby-2.5.0<br>&gt; today + 1<br> =&gt; #&lt;Date: 2018-03-20 ((2458198j,0s,0n),+0s,2299161j)&gt;<br>&gt; today.next<br> =&gt; #&lt;Date: 2018-03-20 ((2458198j,0s,0n),+0s,2299161j)&gt;</pre><p>next_day and prev_day can take a number of days as an argument. Without the argument, they work the same as next and prev.</p><pre># ruby-2.5.0<br>&gt; today + 5<br> =&gt; #&lt;Date: 2018-03-24 ((2458202j,0s,0n),+0s,2299161j)&gt;<br>&gt; today.next_day(5)<br> =&gt; #&lt;Date: 2018-03-24 ((2458202j,0s,0n),+0s,2299161j)&gt;</pre><p>Need to go further? Try next_month or next_year.</p><pre>#ruby-2.5.0<br>&gt; today.next_month(5)<br> =&gt; #&lt;Date: 2018-08-19 ((2458350j,0s,0n),+0s,2299161j)&gt;<br>&gt; today.next_year(5)<br> =&gt; #&lt;Date: 2023-03-19 ((2460023j,0s,0n),+0s,2299161j)&gt;</pre><p>Finally, the &lt;&lt; and &gt;&gt; operators can be used to backtrack or advance a given number of months.</p><pre># ruby-2.5.0<br>&gt; today &gt;&gt; 5<br> =&gt; #&lt;Date: 2018-08-19 ((2458350j,0s,0n),+0s,2299161j)&gt;</pre><h4>Further Reading</h4><p>Check out Rob Dodson’s great <a href="http://robdodson.me/playing-with-ruby-dates/">article</a> about Date, Chronic, and Active Support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62fec30fcf01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/defmethod-works/nine-interesting-tidbits-about-dates-in-ruby-62fec30fcf01">Nine Interesting Tidbits About Dates In Ruby</a> was originally published in <a href="https://medium.com/defmethod-works">Def Method</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intermittent Test Failures with FactoryBot, Faker, and Apostrophes]]></title>
            <link>https://randallreedjr.medium.com/intermittent-test-failures-with-factorygirl-faker-and-apostrophes-b47a26288fc4?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/b47a26288fc4</guid>
            <category><![CDATA[ascii]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Wed, 10 May 2017 16:40:23 GMT</pubDate>
            <atom:updated>2018-08-27T20:16:27.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0syxG6pVAgyWwItiegWS8g.jpeg" /><figcaption>source <a href="https://www.pexels.com/photo/man-in-white-shirt-using-macbook-pro-52608/">https://www.pexels.com/photo/man-in-white-shirt-using-macbook-pro-52608/</a></figcaption></figure><p>I love <a href="https://github.com/thoughtbot/factory_bot_rails">Factory Bot</a>. It allows for simple, repeatable creation of objects for testing, as well as semantic naming. You can have an invitation factory, a pending_invitation factory, and an accepted_invitation factory, and immediately you have some context about the object you’re working with.</p><p><a href="https://github.com/stympy/faker">Faker</a> really takes FactoryBot to the next level. Instead of populating object attributes with arbitrary strings, you can specify an object type that is representative of the data you would expect (e.g. a Name, a Number, or a Business). The wide array of object types you can generate is truly <a href="https://github.com/stympy/faker/tree/master/doc">staggering</a>. Faker also makes your test suite more robust, as repeated runs are more likely to uncover edge cases than if you came up with all of the test values yourself.</p><p>But I was running into an issue with the way I was using Faker and FactoryBot that was causing a huge headache — intermittent test failures. It would happen whenever Faker generated a string with an apostrophe in it — a name like “O’Malley” or a business like “Ed’s Truck Stop.” Then, when I would run a test looking for that string in a view template, the test would fail!</p><pre>Failure/Error: expect(page.body).to include(business.name)</pre><pre>-Strosin, Blanda and O&#39;Kon<br>+Strosin, Blanda and O&amp;#39;Kon</pre><p>The issue was easy to identify, but the solution was a bit more difficult to unearth. At first I tried the traditional method of escaping HTML, but that did not work; escape_html actually generates a slightly different escaped string, displaying the <a href="http://www.asciitable.com/">ASCII value</a> of the escaped character in hexadecimal (x27) instead of decimal (39).</p><pre>&gt; Rack::Utils.escape_html(&quot;Strosin, Blanda and O&#39;Kon&quot;)<br> =&gt; &quot;Strosin, Blanda and O&amp;#x27;Kon&quot;</pre><p>Next, I attempted fixing this by removing the &#39; character from any generated test string.</p><pre>business.name = business.name.delete(&quot;&#39;&quot;)</pre><p>However, that approach was clunky and stopped working as I found other characters that led to the same issue, such as &amp;.</p><p>Finally, I realized that the escaping was not happening in Rack, but rather ERB as it was populating the template.</p><pre>&gt; ERB::Util.html_escape(&quot;Strosin, Blanda and O&#39;Kon&quot;)<br> =&gt; &quot;Strosin, Blanda and O&amp;#39;Kon&quot;</pre><p>Using ERB’s html_escape worked! So all I had to do was update the spec, and everything passed.</p><pre>expect(page.body).to include(ERB::Util.html_escape(business.name))</pre><p>Alternatively, you can use the more succinctCGI class.</p><pre>expect(page.body).to include(CGI.escapeHTML(business.name))</pre><p>For more reading, see this Stack Overflow answer for an excellent, in-depth explanation.</p><p><a href="http://stackoverflow.com/a/41944945/1951290">Rspec controller test failing with Apostrophe Character?</a></p><p><strong>UPDATE</strong> (August 27, 2018): I recently ran into this issue again, but this time with JSON encoding turning &amp; into \u0026. At this point, I’m happy to just use</p><pre>name { Faker::Commerce.department.gsub(&#39;&amp;&#39;,&#39;and&#39;) }</pre><p>I have also updated the article to reflect the <a href="https://github.com/thoughtbot/factory_bot/blob/master/NAME.md">replacement of FactoryGirl with FactoryBot</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b47a26288fc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nil and Presence in Ruby on Rails]]></title>
            <link>https://medium.com/defmethod-works/nil-and-presence-in-ruby-on-rails-cc05f467e0f4?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc05f467e0f4</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Mon, 05 Dec 2016 20:00:36 GMT</pubDate>
            <atom:updated>2016-12-05T21:11:16.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54IMsSRRfssGKUA_2dCteQ.jpeg" /><figcaption>Image credit: <a href="http://in3xplicit.deviantart.com/art/DESTINY-QHD-280077385">http://in3xplicit.deviantart.com/art/DESTINY-QHD-280077385</a></figcaption></figure><p>One of the things I love about Ruby is nil. It can represent nothing and, since every expression in Ruby has a return value, nil is also a useful proxy for certain behavior.</p><p>For example, nil can represent that a variable was never assigned a value, or that a method never executed any statements.</p><pre>def method_that_might_do_something(some_condition)<br>  if some_condition<br>    // do some stuff<br>    return true<br>  end<br>end</pre><p>When an if statement’s condition is fulfilled, that if statement returns the return value of the last expression evaluated inside the block. <strong>However, if the condition fails, the </strong>if<strong> statement returns </strong>nil<strong>.</strong></p><p>So if we want to determine whether <em>method_that_might_do_something</em> executed any statements, we can just use something like:</p><pre>foo = method_that_might_do_something<br>if foo<br>  # do something else dependent on foo<br>end</pre><p>This also comes in useful if you have a variable that is assigned a value under certain execution paths and you want to provide a default otherwise. Since nil is falsey, it can be combined with a more meaningful result via the OR operator (||).</p><pre>return some_string || some_default_string</pre><h3>A Wrinkle in Nil</h3><p>But what if <em>some_string</em> will be an empty string (‘’) instead of nil? We have a problem…</p><pre># irb<br>&gt; ‘’ || ‘default’<br>=&gt; &quot;&quot;</pre><p>An empty string is truthy in Ruby, so in this case, the code above would return “”. If you still wanted to preserve the same default string functionality, you would need to add some additional logic.</p><h3>Presence to the Resuce</h3><p>When I encountered this behavior recently in a Rails project, my first thought was to utilize a ternary operator, which was okkkk…</p><pre>some_string.present? some_string : some_default_string</pre><blockquote>But looking at that code, my rails-sense started tingling.</blockquote><p>Repeating <em>some_string</em> was redundant, and I had a hunch Rails had implemented a better way to handle this circumstance. And indeed it had — presence!</p><pre>some_string.presence || some_default_string</pre><p>A cousin of present?, presence returns the object if present? would evaluate to true, and nil otherwise.</p><pre># rails console<br>&gt; &#39;&#39;.present?<br>=&gt; false<br>&gt; &#39;&#39;.presence<br>=&gt; nil<br>&gt; &#39;default&#39;.present?<br>=&gt; true<br>&gt; &#39;default&#39;.presence<br>=&gt; &quot;default&quot;</pre><p>Plugging this in allows us to use our original code with only a minor variation, and now it handles both nil and empty string perfectly! Delightful.</p><p><strong>Note: Due to it’s relation to present?, presence is only available in Rails, not in vanilla Ruby.</strong></p><p><em>Want to work with me? Def Method is </em><a href="https://www.defmethod.com/were-hiring/"><em>hiring</em></a><em> and accepting new </em><a href="https://www.defmethod.com/services/"><em>clients</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc05f467e0f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/defmethod-works/nil-and-presence-in-ruby-on-rails-cc05f467e0f4">Nil and Presence in Ruby on Rails</a> was originally published in <a href="https://medium.com/defmethod-works">Def Method</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharable ESLint Config]]></title>
            <link>https://medium.com/defmethod-works/sharable-eslint-config-b96af3b93960?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/b96af3b93960</guid>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Thu, 13 Oct 2016 14:50:53 GMT</pubDate>
            <atom:updated>2016-10-18T03:39:01.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCFA4DBrPpAuV7KtZVEoJQ.jpeg" /><figcaption>How we used to share things. Image credit: <a href="https://www.pexels.com/photo/white-compact-disc-93388/">https://www.pexels.com/photo/white-compact-disc-93388/</a></figcaption></figure><p>I had been working on a new React project, and setting up our <a href="http://eslint.org/">ESLint</a> linter, when I came across an irksome linter error:</p><blockquote>error ‘enzyme’ should be listed in the project’s dependencies, not devDependencies — import/no-extraneous-dependencies</blockquote><p>I am importing <strong><em>shallow</em></strong> and <strong><em>mount</em></strong> from enzyme, but they are certainly not runtime dependencies. How to make eslint understand that? As with any vexing linter rule, the easiest approach is just to disable it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc1c3dc6705171fbb1598cffae37c14f/href">https://medium.com/media/cc1c3dc6705171fbb1598cffae37c14f/href</a></iframe><blockquote>I don’t want to have to <strong>remember</strong> to add these lines every time.</blockquote><p>But then, as I added more test files, I thought, “I don’t want to have to remember to add these lines every time.” In reading the ESLint <a href="http://eslint.org/docs/user-guide/configuring#using-configuration-files">documentation</a>, I came across this gem:</p><blockquote>ESLint will automatically look for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem. This option is useful when you want <strong>different configurations for different parts of a project</strong> or when you want others to be able to use ESLint directly without needing to remember to pass in the configuration file.</blockquote><p>Eureka! So I moved our .eslintrc file out of our root directory and into our <strong><em>src</em></strong> directory, then created a duplicate .eslintrc file in our <strong><em>test</em></strong> directory. Then, I turned off the “import/no-extraneous-dependencies” rule in the test directory. Problem solved!</p><blockquote>We should all cringe anytime he hear something like “duplicate file”…</blockquote><p>Well…mostly. We should all cringe anytime he hear something like “duplicate file” as we imagine all of the pain that will be caused from trying to keep those files *NSYNC…er in sync.</p><p>Fortunately, ESLint has a solution from that as well. Just like how you can use <em>“extends”: “airbnb”</em> to use AirBnb’s linter config as the basis for your own, you can extend from your own <a href="http://eslint.org/docs/developer-guide/shareable-configs#local-config-file-resolution">local configuration</a>! So our <em>test/.eslintrc</em> file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4c4a82c2903ce65bb03261f82eb1bfe/href">https://medium.com/media/e4c4a82c2903ce65bb03261f82eb1bfe/href</a></iframe><p>Now we can utilize all of the same linter rules, except for the ones we explicitly override for the test directory. Nice!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b96af3b93960" width="1" height="1" alt=""><hr><p><a href="https://medium.com/defmethod-works/sharable-eslint-config-b96af3b93960">Sharable ESLint Config</a> was originally published in <a href="https://medium.com/defmethod-works">Def Method</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Switched from Sublime to Atom]]></title>
            <link>https://medium.com/defmethod-works/why-i-switched-from-sublime-to-atom-84eed59dd765?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/84eed59dd765</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[atom-text-editor]]></category>
            <category><![CDATA[sublime-text-3]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Tue, 02 Aug 2016 04:11:09 GMT</pubDate>
            <atom:updated>2016-08-02T04:11:09.375Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A programmer’s text editor is a very personal choice. I will always look back fondly on the time Sublime Text and I spent together, but eventually we grew apart. Now there’s a new text editor in my life, and I couldn’t be happier.</em></p><h4>Before Sublime, I didn’t know what I was missing</h4><p>Writing Ruby in Sublime Text 2 was my first time using a modern text editor. Before I became a web developer (back in my Visual Studio days), I thought upgrading Notepad to Notepad2 or Notepad++ was all I could ever need.</p><blockquote>Look that those line numbers! It highlights matching parens!</blockquote><blockquote>-A naive me</blockquote><p>Then I was introduced to Sublime Text as part of the pre-work for the <a href="http://flatironschool.com/">Flatiron School</a>, a web development immersive program, and my eyes were opened.</p><p>Sublime Text was soooo much better than what I had been using all of my life! You could easily select multiple instances of a chunk of text (⌘+D), duplicate selections (⌘+⇧+D), create multiple cursors (⌘+click), and <a href="http://docs.sublimetext.info/en/latest/reference/keyboard_shortcuts_osx.html">so much more</a>!</p><p>So when I heard about Atom, I thought ‘It can’t be <em>that</em> different,’ and subsequently ignored it for a long time. A few months ago, I installed Atom so that I would have it available for pairing interviews if the candidate preferred. Slowly but surely, I have discovered features that have confirmed that I will never go back to Sublime. Here are a few of the most compelling ones.</p><h4>1. Highlighting Changed Files</h4><p>The first thing that caught my eye about Atom, and prompted me to keep trying it out, was <strong>changing the color of filenames</strong> based on their state. Whenever you add a new file, the filename shows up as green in the file tree in the side bar. Changed files are displayed in yellow, and that color scheme is applied recursively to the containing folders. This makes it a lot easier to find the files you’re working on at a glance, and also serves as a reminder to commit your changes periodically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*Om7RyobGTAGzNwK4VKu48w.png" /></figure><h4>2. Resolving Whitespace Errors</h4><p>To be honest, I don’t know why the Ruby Style Guide prescribes <a href="https://github.com/bbatsov/ruby-style-guide#no-trailing-whitespace">not having any whitespace at the end of each line</a>, nor why <a href="https://github.com/bbatsov/ruby-style-guide#newline-eof">every file must end with an empty line</a>, but I try (not very hard) to follow the convention. Github conveniently highlights this extra whitespace in your diffs, and I have made a few PR rebases to address them, but it was only ever a minor nuisance.</p><p>Then I started working with a new team on a React project with a very fastidious linter that would cause our local test runs and CI builds to fail for any extra whitespace. It became a huge headache! Fortunately, I had recently discovered that Atom <strong>automatically resolves some whitespace errors</strong> for you whenever you save a file, and handily convinced my pair to switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*nr59cSHRfygrrwl9vVZD-w.gif" /><figcaption>Saving a file with whitespace errors in Atom</figcaption></figure><h4>3. It’s Free!</h4><p>So I don’t mind paying for software that I find useful, including Sublime Text. But software licenses can be tricky. It’s okay for me to use my personal license on my work laptop, as long as I remove it when I return the computer to my employer. But as a consultant, I cannot install my license on every pairing machine I use, nor do I want to ask my clients for licenses. The Sublime pop-up prompting you to purchase a license is a minor annoyance, but abrupt enough to interrupt your flow. On the other hand, <strong>Atom is open source</strong> and free to use.</p><h4>4. Out-of-the-box Executable</h4><p>Granted, setting up your Sublime Text <em>subl</em> symlink only takes a minute, but it requires me to remember enough commands that it’s a discrete step on my personal ‘New Computer Setup’ gist. When you install Atom, <strong>you can run <em>atom .</em></strong> from the command line immediately — no need for symlinks, path variables, or re-sourcing your bash profile.</p><h4>5. Simpler package installation and preference management</h4><p>Every time I wanted to search for and install a package in Sublime, I would have to google the command to bring up the menu (for your reference, ⌘+⇧+P then search for and select Package Control: Install Package). Similarly, I keep a gist file of my Sublime preferences so I can easily apply them on a new installation. With Atom, the user experience is refreshingly simple. <strong>Package installation is intuitive </strong>and the settings menu looks how you would expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQ6CaEWor2Aq9wUrOiWlPw.png" /><figcaption>Sublime and Atom settings side by side for comparison</figcaption></figure><p>And last but not least…</p><h3>6. Dragging and dropping files!</h3><p>Ok so this one I just discovered, and I still can’t believe it. I cannot tell you how many times (innumerable) I have tried to move a file between directories in Sublime Text by dragging it as you would in any other file explorer interface. Even though I know it doesn’t work, I still find myself futilely clicking and dragging periodically. Then I tried it in Atom, fully expecting the UI to not respond at all, like it always doesn’t, when suddenly the file moved and the name turned green (see #1)! This was the last straw that burned my bridge to ever returning to Sublime Text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*mGFj4gwqGoQRo5lL3fBDIQ.gif" /><figcaption>What is this, magic???</figcaption></figure><p>Note: I know some (all?) of the features I have described here are available in Sublime as installable packages, but honestly I’m not the kind of person to search these packages out. It would appear that Github took a page out of Apple’s playbook when building Atom and created something that ‘<a href="https://www.youtube.com/watch?v=qmPq00jelpc">just works</a> (seamlessly)’, and I am <a href="http://9to5mac.com/2012/08/24/tim-cook-tells-apple-employees-that-todays-victory-is-about-values/">delighted</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84eed59dd765" width="1" height="1" alt=""><hr><p><a href="https://medium.com/defmethod-works/why-i-switched-from-sublime-to-atom-84eed59dd765">Why I Switched from Sublime to Atom</a> was originally published in <a href="https://medium.com/defmethod-works">Def Method</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Declarative Programming in Ruby]]></title>
            <link>https://medium.com/defmethod-works/declarative-ruby-programming-4b5c62719d6b?source=rss-62e3adfb5b22------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b5c62719d6b</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Randall Reed]]></dc:creator>
            <pubDate>Mon, 07 Mar 2016 01:02:18 GMT</pubDate>
            <atom:updated>2016-03-07T01:04:53.595Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been programming in Ruby for almost two years now, and sometimes I forget how hard it was for me to wrap my head around the Ruby approach to solving problems. Finally, Tyler Mcginnis has given me the vocabulary to describe the paradigm shift I experienced — Imperative vs Declarative code.</p><blockquote>With imperative code, you’re telling your program <strong>how</strong> to do something. And with declarative code, you’re telling your program <strong>what</strong> you want to do.</blockquote><blockquote>-Tyler Mcginnis, <a href="http://courses.reactjsprogram.com/courses/reactjsfundamentals/lectures/760073">React Fundamentals</a></blockquote><p>Coming from a C++ background, I was used to imperative programming; those mental pathways were well-trodden. Although Ruby can be used to write imperative code, its expressiveness makes declarative code possible. The ‘each’ method was a revelation to someone who had been writing ‘for’ and ‘while’ loops for years.</p><h4>Example: Performing an operation on every element of an array</h4><ul><li>Imperative Anti-pattern: Manually keeping track of array index</li></ul><pre>i = 0</pre><pre>while i &lt; array.length do</pre><pre>  puts array[i]</pre><pre>end</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Array.html#method-i-each"><strong>#each</strong></a></li></ul><pre>array.each do |element|</pre><pre>  puts element</pre><pre>end</pre><p>However, Ruby doesn’t stop there. If you still find yourself defaulting to using each for every problem and using local variables to keep track of state, consider whether a simpler solution exists. Here are some anti-patterns to watch for, along with iterators that will make your code more declarative.</p><h3>Anti-patterns in Ruby Iterators</h3><h4>Creating a new array from an existing array</h4><ul><li>Desired return type: Array</li><li>Imperative Anti-pattern: Manually adding elements to new array</li></ul><pre>squares = []</pre><pre>array.each do | element |</pre><pre> squares &lt;&lt; element ** 2</pre><pre>end</pre><pre>squares</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-collect"><strong>#collect</strong></a></li></ul><pre>array.collect { | element | element ** 2 }</pre><h4>Returning a subset of an array satisfying criterion</h4><ul><li>Desired return type: Array</li><li>Imperative Anti-pattern: Manually adding elements to new array</li></ul><pre>odds = []</pre><pre>array.each do | element |</pre><pre> odds &lt;&lt; element if element.odd?</pre><pre>end</pre><pre>odds</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-select"><strong>#select</strong></a></li></ul><pre>array.select { | element | element.odd? }</pre><h4>Returning the first element of an array satisfying a certain criterion</h4><ul><li>Desired return type: Object (whatever class the element is)</li><li>Imperative Anti-pattern: Using a local variable to store element</li></ul><pre>first_positive = 0</pre><pre>array.each do | element |</pre><pre> first_positive = element if element &gt; 0</pre><pre>end</pre><pre>first_positive</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-detect"><strong>#detect</strong></a></li></ul><pre>array.detect { | element | element &gt; 0 }</pre><h4>Determining the number of elements of an array satisfying a certain criterion</h4><ul><li>Desired return type: Integer</li><li>Imperative Anti-pattern: Manually incrementing a counter</li></ul><pre>match_count = 0</pre><pre>array.each do | element |</pre><pre> match_count += 1 if element % 10 == 0</pre><pre>end</pre><pre>match_count</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-count"><strong>#count</strong></a></li></ul><pre>array.count { | element | element % 10 == 0 }</pre><h4>Determining whether any elements of an array share a certain characteristic</h4><ul><li>Desired return type: Boolean</li><li>Imperative Anti-pattern: Manually toggling a boolean flag</li></ul><pre>is_present = false</pre><pre>array.each do | element |</pre><pre> is_present = true if element &lt; 0</pre><pre>end</pre><pre>is_present</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-any-3F"><strong>#any?</strong></a></li></ul><pre>array.any? do | element |</pre><pre> element &lt; 0</pre><pre>end</pre><h4>Determining whether all elements of an array share a certain characteristic</h4><ul><li>Desired return type: Boolean</li><li>Imperative Anti-pattern: Manually toggling a boolean flag</li></ul><pre>all_even = true</pre><pre>array.each do | element |</pre><pre> all_even = all_even &amp;&amp; element.even?</pre><pre>end</pre><pre>all_even</pre><ul><li>Declarative alternative: <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-all-3F"><strong>#all?</strong></a> (or <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-none-3F"><strong>#none?</strong></a>)</li></ul><pre>array.all? do | element |</pre><pre> element.even?</pre><pre>end</pre><h3>Conclusion</h3><p>Once you’ve gotten the hang of declarative programming, imperative programming begins to feel a bit like micro-managing. Learn to let the details go; stop worrying about managing state and put Ruby’s iterators to work for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b5c62719d6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/defmethod-works/declarative-ruby-programming-4b5c62719d6b">Declarative Programming in Ruby</a> was originally published in <a href="https://medium.com/defmethod-works">Def Method</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>