<?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 Christian Tith on Medium]]></title>
        <description><![CDATA[Stories by Christian Tith on Medium]]></description>
        <link>https://medium.com/@cttith?source=rss-4397185a838------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0cznNVxFUBeK5iyL</url>
            <title>Stories by Christian Tith on Medium</title>
            <link>https://medium.com/@cttith?source=rss-4397185a838------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:05:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cttith/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[Relative Ruby: How Ruby Measures Up Against the Competition]]></title>
            <link>https://medium.com/plp-ruby/relative-ruby-how-ruby-measures-up-against-the-competition-85b2c0d0e239?source=rss-4397185a838------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b2c0d0e239</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[platuh]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Christian Tith]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 07:34:53 GMT</pubDate>
            <atom:updated>2019-04-22T07:37:52.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*RThFtrkPqCjNyjbed4TVCQ.png" /></figure><h3>Benchmarking Speed</h3><p>Benchmarking is form of program testing wherein the performance of the code is compared against some set standard or point of reference. A useful benchmark test must have two essential properties: quantifiability and repeatability. Quantifiability means that the test produces a numeric measurement which can be compared relationally (i.e., greater than, equal to, less than); despair, for example, is an unquantifiable concept, while number of pickles eaten is perfectly quantifiable. Repeatability means that the test can be applied over and over again in quick succession, which ensures that the benchmarking computes a performance value that absorbs any outlier over-/under-performing runs.</p><p>The most popular benchmarking method is the measurement of execution time, or how long it takes a program to run; in Ruby, this sort of benchmarking is achieved via the Benchmark module. In addition to many more sophisticated methods, there are two basic benchmarking modes found in the Ruby Benchmark module: Benchmark.measure and Benchmark.bm.</p><p>The Benchmark.measure method evaluates a section of encapsulated code by running the code, measuring its execution times, then repeating the process many times over until a set testing limit is reached, at which point a series of time values are printed to the command line.</p><p>Below, for example, is a benchmark testing the performance of a short array deletion program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*86BCzwE6qEeVU4NLLMrBeQ.png" /><figcaption>Code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*247s0zU4To4eLn1k5mRg1Q.png" /><figcaption>Output</figcaption></figure><p>As indicated by the #.times phrase preceding the do statement, this benchmark runs the code snippet 100,000 times in a row. If this number is large, indicating that many tests have been run, then we expect that multiple run-throughs will produce similar measurements, whereas a smaller number (fewer tests) will produce measurements that vary greatly each time.</p><p>The measurements produced each quantify a different segment of the code’s overall execution time(s) in seconds. Specifically, we can say…</p><p>· The first number describes the time spent executing the code on the processor (known as the user CPU time)</p><p>· The second number describes the time spent executing the code in the operating system (known as the system CPU time)</p><p>· The third number is the sum of the first two numbers</p><p>· The fourth number is the actual amount of time it took for the code to execute</p><p>These numbers are useless, however, in the absence of a reference point or points. To compare our code snippet to another, similarly-purposed Ruby program, we can use the Benchmark.bm method to run multiple code samples for easy comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*2ouaz6EVjQkuB48PagtvEQ.png" /><figcaption>Code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*3s7VWHULIOXszL_C2CR6vg.png" /><figcaption>Output</figcaption></figure><p>Now, we can see that our original program was inefficient; it performed slower than the new version at all points during its execution.</p><p>Alternatively, you may want to compare the speed of a program in Ruby to the speed of a similar program in a completely different language. This is less easily accomplished than Ruby-to-Ruby comparisons; however, there are many repositories online that store relative performance values for specific algorithms/programs in different languages, Ruby included. If need be, you can also perform a customized analysis by writing multiple versions of a program, timing each version’s respective execution time using whatever benchmarking tools are available for that specific language, and then manually comparing the results. In general, expect Ruby programs to run slower than statically typed and/or complied languages like C or Java, since Ruby is dynamically typed and interpreted. Ruby programs also tend to suffer performance-wise due to inefficient garbage collection, slow method calls, and a lack of true multithreading support.</p><h3>Safety</h3><p>In programming languages, safety describes the degree to which a language safeguards against programmer-generated errors. Some languages, for example, do not require manual memory deallocation, instead leaving that task up to the computer. This way, programmers do not have to worry about catching redundant deallocations or accidentally clearing memory too early. afer languages notice errors earlier. This means that error-catching that occurs at compile time results in better overall safety than error-catching at run-time, though both scenarios are superior those where errors are not caught at all.</p><p>Ruby is not considered a particularly safe language, since it fails to catch most errors (indexing issues, null pointers, type confusion) prior to run-time; however, it does have a few notable defenses. One of Ruby’s best-known safety features is its garbage collection system, which automatically detects and corrects unnecessary memory use. As in the first example, this allows programmers to delegate the work of memory management to the machine, reducing errors. Another important safety aspect of Ruby is its error response system; specifically, if a Ruby program encounters an error, that error is detected in run-time and the program either crashes or throws an exception. This makes Ruby safer by forcing a faulty program to halt, rather than allowing it to continue and produce malformed output down the line.</p><p>Additionally, one useful tool that Ruby provides for do-it-yourself safety purposes is the safe navigation operator, (&amp;.). When attached between an object and one of its methods or members, this operator can check if said method/member exists (i.e., is not nil). Consider the following example, where student describes an instance of a Student class. Some instances of this hypothetical class may have a member idnum, but are not required to do so; that is, (object).idnum is never given a default value.</p><p>If student was never given an idnum, then the following statement may return an error, depending on its usage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*3Zjf_JG5kwaP77RWgQfgmQ.png" /></figure><p>This statement, however, uses the safe navigation operator to verify idnum’s existence prior to execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*4HGVNLIKqboFff9VCFCeGA.png" /></figure><p>In some ways, the safe navigation operator functions as an if statement, only more compact and specialized.</p><h3>Ease of Use</h3><p>Looking at Ruby from an outside perspective in, compared to compiled programs like Java and C++, the syntax is much more readable. While still more complicated than Python in terms of readability, it is still much easier to understand than Java as there is no typecasting for Ruby. Since everything is an object, there is no need to learn about primitives and their differences. However, as a result, performance in Ruby is much worse than compiled languages.</p><p>In addition, since all variables are automatically assigned to be private, requiring the need for public methods to access these private variables. Memory wise, there is no need to manually manipulate memory in Ruby, as the garbage collector automatically disposes of any unused objects, freeing up large amounts of memory without the concern of creating manual memory releasing errors. Since Ruby itself is a popular language, learning to use it is easier than the lesser known languages, as there are a large number of resources to use to learn.</p><h3>Memory Footprint</h3><p>In order to track the memory footprint, you must install a gem in Ruby. There are two options for installing the gem. The first is simply adding the following into the gem file.</p><pre>gem &#39;memory_profiler&#39;</pre><p>Afterwards, execute the following code, and this will install the gem.</p><pre>$ bundle</pre><p>The other more simple option is simply going and installing it yourself via the following command inside of your terminal,</p><pre>$ gem install memory_profiler</pre><p>Afterwards, using your ruby program, you should add the following lines of code to track the memory.</p><pre>require &#39;memory_profiler&#39;<br><br>MemoryProfiler.start<br><br># run your code<br><br>report = MemoryProfiler.stop<br>report.pretty_print</pre><p>First you must start the memory profiler to track its usage, and run your code accordingly, and then stop your memory profiler object and use the method pretty_print to see a good representation of the memory usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*5MH-Mp--LnlZsRqM-yOAuw.png" /><figcaption>The following code simple adds a string to the array RETAINED 100,000 times.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-JRoUYUTZt0hnd3ymEySA.png" /><figcaption>The example output for the profiler, showing the number of bytes allocated, as well as categories for the allocated objects.</figcaption></figure><h3>Reasons to use Ruby</h3><p>Some of the most common questions people have when learning how to program: “What’s the best language to learn?” or “Why is x better than y?”. This question is entirely subjective and also situational. Do you want to work with low level embedded systems? Learn C. Want to move more towards fast prototyping, web development or scripting? Ruby is your friend. The great thing about Ruby is that its syntax is easy to digest and it is dynamically typed. So whenever you want to reuse a variable and assign it a different ‘primitive’ data type, there’s gonna be no problem.</p><figure><img alt="Image result for dynamically typed" src="https://cdn-images-1.medium.com/proxy/1*D_Ly10_ch7_8vLRWnjBo4w.jpeg" /></figure><p>What’s great about this is that programmers don’t have to feel tied down and restricted. They can move fast and have a product up and running in no time compared to a more restricted language such as C. This isn’t made to discredit C, it has a lot of its own great merits: one being performance. Ruby on the other hand isn’t utilized for performance.</p><p>Ruby really started garnering programmers when Ruby on Rails was introduced. It is a framework used for web development and was popularized by its ease of use, automation and testing. The language blew up and was considered one of the fastest growing in 2005 when Rails was released. This was especially popular with smaller shops that had budgets that weren’t as large as huge corporations and they were more limited on time. Twitter, Groupon, and GitHub are a few websites to name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*2Bdk4JG9KbGFwQQ6.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*6xCjk0ZA5t8t11fO.png" /></figure><p>Lastly, Ruby is great for scripting since it is lightweight and easy to understand syntactically. Things that would take a language like C a hefty amount of code to write, could be written in a line or two in Ruby. This is another factor that is great for companies with shorter timelines and smaller budgets.</p><p>Personally, learning Ruby while having a background in C++ and Java was not too difficult as Ruby is considered an object-oriented language (everything is an object), but refreshing to get more of a functional-type paradigm while learning. I highly encourage programmers of all different backgrounds try to learn a few languages with different paradigms to appreciate each language and also learn a different way of approaching things.</p><p>Written by:</p><p>Christian Tith @cttith</p><p><a href="https://www.linkedin.com/in/christian-tith-43385816a/">https://www.linkedin.com/in/christian-tith-43385816a/</a></p><p>Sarah Fontenot <a href="https://medium.com/u/f5ce5260eb6d">@</a>sarahfontenot11</p><p>LinkedIn: <a href="https://www.linkedin.com/in/sarah-fontenot-43baa1168/">https://www.linkedin.com/in/sarah-fontenot-43baa1168/</a></p><p>Chuong Vu @cvu014</p><p><a href="https://www.linkedin.com/in/chuong-vu/">https://www.linkedin.com/in/chuong-vu/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b2c0d0e239" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plp-ruby/relative-ruby-how-ruby-measures-up-against-the-competition-85b2c0d0e239">Relative Ruby: How Ruby Measures Up Against the Competition</a> was originally published in <a href="https://medium.com/plp-ruby">PLP Ruby</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby: Under the Hood]]></title>
            <link>https://medium.com/plp-ruby/ruby-under-the-hood-63a190a343e9?source=rss-4397185a838------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a190a343e9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Christian Tith]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 05:46:36 GMT</pubDate>
            <atom:updated>2019-04-01T05:46:36.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*CKBytuSPu0XgK7z2.jpg" /></figure><h3>Toolchains</h3><p>Like many other programming languages there is some sort of mechanism under the hood that converts the ruby code that we write and transforms it into byte code that can be interpreted by a virtual machine. There is a built in tool for Ruby called Ripper, it’s a script parser that can give information on several stages of the transformation of ruby code. The three stages are tokenizing, parsing, and compiling. We’re gonna explain these stages of the process and try to break down the ambiguity of what’s going on with our written code.</p><h3>Tokenization</h3><p>Tokenization is the process of breaking up your code into tokens so that it can be passed into a parser to not only see if the order of tokens is valid, but to also be used to create a parse tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*6k3kVbs8N3aTvofs1Xw-OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*14SNyTCdToyGQf1GT7MpZQ.png" /></figure><p>Using ripper we are able to “lex” the code block found in &lt;&lt;CODE …..CODE. The image to the right shows the token in an array format.</p><p>[[line, column], token name, characters, EXPR_]</p><p>This is the first step in the process of making code compile via Ruby.</p><h3>Parsing</h3><p>The next step involves taking the tokens and then putting them together to form what is called an abstract syntax tree, this will show the syntactical meaning of the program. If this stage is reached it means the code written complies to the grammar and is valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*3dMSjO9i1iw53piSmmCCFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*o8x3KpAUJnhpV4450Wc92A.png" /><figcaption>Abstract Syntax Tree</figcaption></figure><p>The output can better be represented by constructing nodes and creating a visual tree, but for the sake of understanding what is happening we’ll explain the meaning behind these lines and how it relates to the grammar.</p><p>So in the image to the right we are receiving the syntax tree representation of the code to the left. The grammar in our language has a terminal when we create identifiers. In this case our identifiers are going to be a “var_field” and a “string_literal”. The root node is going to be “program” and the intermediate nodes are steps we follow in our grammar to reach terminals/leaves found in the tree.</p><p>After we have this tree constructed we can move on to compiling our program</p><h3>Compiling</h3><p>Compiling the program is now possible with the creation of our syntax tree. Ruby transforms the tree into a set of instructions that is fed into a virtual machine to be interpreted. This VM in ruby is called “YARV”, which stands for “Yet Another Ruby Virtual Machine”. There isn’t much code that we can show to visualize what is going on, but we can think of executing the program using a call stack and putting blocks on top of one another and emptying out the stack as we reach the end of our program.</p><p>That’s about it. This is a common sequence of events to create code that will run. Some other languages will have the code transform into machine language to be interacted with directly, instead of feeding byte code into an interpreter. The former is more efficient, but the latter provides for code that can be run on multiple different operating systems.</p><h3><strong>Internal Data Storage</strong></h3><p>When you create variables in a programming language, they are often held in some sort of data structure. In the case of Ruby, the hash table data structure is the stomach of it, being used to hold much of its internal data. With the hash table, it is able to access data in constant time with a good hash function.</p><p>Every time you create a function or a variable, Ruby adds a new element to the hash table. These hash tables organize data by putting it through a hash function and organizing the variables into bins to easily go through them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhuKInfrekDFs_zc3KxeOQ.png" /><figcaption>Example: The diagram above shows exactly how the hash table is computed</figcaption></figure><p>By running the data through the Hash Function, it is able to be split up into specific bins that can be accessed in constant time, assuming the Hash Function is able to separate the data into roughly equally sized bins. To search through the Table, simply recompute the data through the Hash Function and you will get the bin number that it is located in.</p><p>In the case of <em>hash collisions</em>, or a moment when multiple inputs map to the same bin, Ruby solves this by measuring the size of each bin and once the average size reaches greater than a constant amount defined in Ruby’s C code, it will rehash the entries in the table across all of the bins again, spreading them out.</p><h3>Intermediate Representations</h3><p>Unlike C, Fortran, and Haskell, Ruby is an interpreted language. This means that Ruby programs are directly executed without being converted into machine-specific optimized code.</p><p>That being said, Ruby is not without intermediate representations. This is because a Ruby program must be translated by its interpreter into a set of instructions before it can be executed by a Ruby Virtual Machine (VM), a process which greatly resembles the machine language conversion used by compiled languages. These instruction sequences are invisible to programmers, since it is generally unnecessary to examine them in detail; however, it is easy for the interpreter to present them if needed. In this section, we will consider only the YARV (Yet Another Ruby VM) interpreter, since it is an official Ruby interpreter for Ruby versions past 1.9. Other interpreters can also be coaxed into displaying their instruction sequences, but may produce slightly different results due to varying interpretation methods.</p><p>Since Ruby code is usually interpreted by YARV, intermediate representations / instruction sequences in Ruby are often referred to as YARV instructions. These instructions are not as readable as regular Ruby code, since they are optimized for VM interpretation. They can be displayed using the RubyVM::InstructionSequence class…or, more specifically, its encapsulated compile method. This method generates the YARV instructions of any code it receives, then translates them into equivalent, albeit slightly more readable instructions for human perusal. The following code, for example, when run using the command line…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*RyDIJWKpEpf2C8-GpIWseg.png" /></figure><p>Outputs this list of instructions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*KAGMylb_GQE0_FswBPzFzw.png" /></figure><p>Note that the inclusion of “.disasm” at the end of the command allows RubyVM to output the instructions to the command line; otherwise, RubyVM::InstructionSequence.compile() will only output confirmation that the code snippet did, in fact, compile.</p><p>While not completely incomprehensible, these instructions are difficult to read due to their formatting…fortunately, rephrasing the above command as a put statement cleans things up a bit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*8V-Nh0yFw4ab-htv62bi1A.png" /></figure><p>In general, programmers can disregard all the instructions not preceded by a four-digit number. The leave instruction is also frequently ignored, since it simply indicates that a process is being exited. In this example, the important instructions are:</p><p>0000 putobject 3 ( 1)[Li]<br>0002 dup<br>0003 setlocal_OP__WC__0 b</p><p>From this output, we can see that our code snippet creates an object 3, duplicates it, then stores the duplicate in a variable b. If our code instead stored the string ‘hello’, then our YARV instructions would be:</p><p>0000 putstring “hello” ( 1)[Li]<br>0002 dup <br>0003 setlocal_OP__WC__0 b</p><p>What about a more complicated line of code, like one involving multiple objects? Below is the instruction sequence generated by the code “a = 1+2”. Notice that the first putobject instruction is different from the second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*APqAZNLCsxdYmq__JGtKjg.png" /></figure><p>Finally, we compare the output of two very similar InstructionSequence.compile() calls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*VoVZAs8wevrURe0DcqGHPw.png" /></figure><p>As in the previous example, our putobject instruction for the number 1 is different from the others. Further experimentation will show that this is the case regardless of where 1 shows up in the code (i.e., “1 + 2” vs “2 + 1”). This is an example of how intermediate representations like YARV instructions reveal intricacies in how the VM works; since 1 is frequently used for incrementation and is therefore considered a special number, its related instructions are slightly different from those of other objects, though this variance is completely invisible from the outside.</p><p>Written by:</p><p>Christian Tith @cttith</p><p><a href="https://www.linkedin.com/in/christian-tith-43385816a/">https://www.linkedin.com/in/christian-tith-43385816a/</a></p><p>Sarah Fontenot <a href="https://medium.com/u/f5ce5260eb6d">@</a>sarahfontenot11</p><p>LinkedIn: <a href="https://www.linkedin.com/in/sarah-fontenot-43baa1168/">https://www.linkedin.com/in/sarah-fontenot-43baa1168/</a></p><p>Chuong Vu @cvu014</p><p><a href="https://www.linkedin.com/in/chuong-vu/">https://www.linkedin.com/in/chuong-vu/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a190a343e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plp-ruby/ruby-under-the-hood-63a190a343e9">Ruby: Under the Hood</a> was originally published in <a href="https://medium.com/plp-ruby">PLP Ruby</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby: Debugging and Testing]]></title>
            <link>https://medium.com/plp-ruby/ruby-debugging-and-testing-48ae8d19b4fc?source=rss-4397185a838------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ae8d19b4fc</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Christian Tith]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 07:35:02 GMT</pubDate>
            <atom:updated>2019-03-20T07:35:02.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*pe9XPzzyDr5wqpfidS3eWA.png" /></figure><h3><strong>Debugging</strong></h3><p>The art of debugging, we all have our own methods of finding the root of problems. Some of us, probably many beginners (including myself), do so by strategically placing print statements throughout the section we believe to be causing errors. In Ruby there’s a way to unload all of the contents of a data structure if needed. You can do so by printing the structure followed with “.inspect” with puts. Alternatively, Ruby allows you to place a “p” in front of the data structure to unload its contents. This generates a string of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mU68OyFGclutnjAYv8i74w.png" /><figcaption>puts with <strong>.inspect</strong> and <strong>p</strong></figcaption></figure><p>As you can see from the snippets above, the content of the array is unloaded and is a nice feature to have to know what all is stored. Now this is something that can have a wide range of uses, one of the more useful ones that come to mind is finding out what all is stored when we aren’t sure.</p><p>Now that we have gone over simple print-tracing, we can look at a more explicit problem that we get from a stack trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxjPq8FHJjXueLfmrU5xbQ.png" /><figcaption>Stack trace</figcaption></figure><p>So reading this stack trace we can break this down into 4 distinct lines</p><ol><li>“Uncaught exception: undefined local variable or method ‘undefined_string’ for main:Object”</li><li>/Path…./main.rb:2:in ‘&lt;top (required)&gt;</li><li>/Path…/rdebug-ide:23:in ‘load’</li><li>/Path…/rdebug-ide:23:in ‘&lt;main&gt;’</li></ol><p>The first line is pretty straight forward, we are trying to print out a variable named “undefined_string” that we haven’t defined.</p><p>The second line is saying in line 2 of file “main.rb” there is some sort of failure. The &lt;top (required)&gt; is saying that the file that we ran, in our case “main.rb”, came up with an error. This is helpful if we have a file that uses a library and the code within the library contains some error. We can pinpoint which file we are running that is causing the problem, this is extremely helpful when we have multiple dependencies and a huge hierarchy of files.</p><p>The third and fourth line can be bunched together and are coming from the rdebug-ide.rb file generated by the ruby-debug-ide gem installed to allow debugging for Ruby on VSCode. The rdebug-ide.rb file is a generated file by RubyGems and is used to facilitate the ruby-debug-ide gem. This is the file tells lets the editor know when there is a problem.</p><p>These are some ways that we can utilize tools that are provided when working with Ruby code to debug. Another very important one is the debugger that is provided with your editor, in this case VSCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*qWPc7NO1zBhiZvEVo562OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiX4xj-pHMNVzUgVeED4wQ.png" /><figcaption>VSCode debugger tools</figcaption></figure><p>The debugger is a great tool to “walk through” your code. It allows the programmer to set a break point indicated by the “red dot” to the left of the line numbers. The picture to the right is representative of a program being debugged with a break point. A small toolbox appears with a few symbols near the top of the editor and to the left of the editor four tabs appear : Variables, Watch, Call Stack, Breakpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*5fCfFm1-3cOt1KoW8f_LhA.png" /><figcaption>Debugger toolbox</figcaption></figure><p>Starting from the left the first button(play button) is “Continue”, it will continue the execution of the program to the next available breakpoint if available or to the end of the program. The second button (arrow pointing right) is “Step Over”, this will go to the next line and start filling the tabs with information about variables that have been defined, methods being called, and current state of call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9ssk1CFL19nTGHeKbnlng.png" /><figcaption>debug_Arr initialized</figcaption></figure><p>From the above picture there is a yellow pentagon located on line 5, this indicates that we are going to execute this line of code next. Which means that we have executed every line before this. This can be seen underneath the “variables” tab to the left, underneath “Local” we can see an indent that contains “debug_Arr: Array ( 4 elemen….)”. This shows us what has been initialized so far and we are able to see its contents by expanding the tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*D1qdHujq-C5dbNjhBaonOQ.png" /><figcaption>Variables initialized</figcaption></figure><p>As seen above, we have initialized debug_Arr and we’re able to see its contents. This is a feature that is undoubtedly useful, especially when we run in to some undefined behavior in our code. We can utilize the current state of the program and “Step Over” code to see what happens before an error occurs.</p><p>Going back to the buttons on the debugger tool, the third button (arrow pointing down) represents “Step Into”, this will allow you to internally walk through a method if it is called on. For example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*-i_XJYkR-I9SMXM2DlvH3w.png" /><figcaption>Step In functionality</figcaption></figure><p>Here we created a method “HelloWorlds” and we set a break point on the function call. We are going to “Step In” to the function to see where the debugger takes us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*FXgfbq0ROCwcU0E-JFasZA.png" /><figcaption>Stepping in method</figcaption></figure><p>As you can see the yellow pentagon, after pressing “Step In”, the debugger takes us inside the method being executed in line 7. This is great when you need to figure out why a method is returning something that you aren’t expecting or if it’s throwing an error.</p><p>Moving on to the fourth button (arrow pointing up) this button represents “Step Out”, this will leave the current method being walked through and go to the next method found on the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*UMb93a_GqpVDsg7w8Ylc6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*iLPt7qeZLhAD2zmX8x7LHQ.png" /><figcaption>Step Out vs Step in</figcaption></figure><p>The picture to the left represents the state of the debugger when “Step In” is pressed twice. The picture to the right represents the state of the debugger (finished) when “Step In” is pressed once and “Step Out” following. This is useful when you are debugging and find out that the nested function call performs fine and you would like to skip to the next line from the call stack.</p><p>Lastly, the fifth button ( Green arrow ) represents Reset, what this does is take you back to the beginning state of the debugger when the program was executed; back to the breakpoint.</p><p>Debugging is important in understanding where things went wrong and can save you from headaches when you’re not sure what to do when problems arise. A lot of different editors have their own debugger and for the most part they’re all pretty similar in functionality. Debugging is a must-have in your toolkit as a programmer.</p><h3><strong>Testing</strong></h3><p>Testing is an essential part of programming to ensure that code does what is expected. There is other software that you can download and install to perform testing on your ruby programs. Such programs include Test::Unit (Included in Ruby), Shoulda, RSpec, MiniTest, and Cucumber to name a few. When unit testing it is not necessary to test the entire system because there are somethings that can’t be tested.</p><p>Here I’ll demonstrate an example using Linux. Below is a simple example of a test to see if the function cap(name) actually changes all the letters of the name to uppercase. First declare your own class, in this case is TestDemo and then you would have to import the library for testing which is “require ‘test/unit’” and then you would create another class for a test case. Note that depending what kind of tests you want to implement a specific library has to be imported. Here we’ll name it TestCase and it is important to to include “&lt; Test::Unit::TestCase” to implement testing. Note that the class name and the included word are not the same. The class name could have been any other name and the string will not change. Then, inside the class write a function for the test case. Most test case are written as “assert[…]” with […] completing the name of the test that exist. Here in this example we have assert_equal( , ) having two parameters, the first representing the expected output (“MICHAEL”) and the second representing the test input (TestDemo.new.cap(“michael”)). After running the script in the terminal, which runs the test as well, the results will be shown and will tell whether it pass or fails the test as shown in the second image below. In this case our test passes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFc0fbnbzn6YMrwuBhQSCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*kv5V431-tBAI85NvgLwu_A.png" /></figure><p>There are many tests that can be implemented such in the Test::Unit::Assertions method such as assert, assert_block, assert_equal, assert_no_match, assert_not_equal, assert_not_nil, assert_not_same, assert_not_send, assert_nothing_raised, assert_nothing_thrown, assert_raise, assert_respond_to, and assert_send.</p><p>Test::Unit itself contains other modules as well such as Test::Unit::[Assertion, AutoRunner, AutoRunner::Runner, GCStressOption, GlobOption, LoadPathOption, Options, ProxyError, RequireFiles, RunCount, Runner, Runner::Worker, StatusLineOutput, TestCase, Worker]. Within those modules are the methods that can be used to test code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Furn2sAjf1HU%3Fstart%3D3%26feature%3Doembed%26start%3D3&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Durn2sAjf1HU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Furn2sAjf1HU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ba4c53a2c48cd9e8e5aa4eb9f533669/href">https://medium.com/media/2ba4c53a2c48cd9e8e5aa4eb9f533669/href</a></iframe><h3>Unit Testing Framework</h3><p>Error resolution has two steps: finding the bugs, and fixing them. Debugging, as described above, is the process of fixing errors in code. This step cannot be automated efficiently, since most programs cannot repair themselves…finding bugs, however, is a different issue entirely. The previous examples dealt with using tools such as .inspect, VSCode, and carefully place print statements to pinpoint issues; however, these methods all require significant user input, and unlike debugging, error location can be at least somewhat automated through the use of unit testing.</p><p>When biologists are studying an animal, they have to choose what level of complexity to use when performing their analyses. They could simply consider the creature in question as a collection of organs…but it is equally reasonable to view it as a collection of cells, or even a mass of atoms. Similarly, programmers can split up their programs in many different ways; for example, they can view each line as an independent component, or each function, or each loop. In unit testing, the basic element of code used is called a unit. Units are the smallest independently-testable segments of a program. This block of code, for example, is a unit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*70qZhk1CuOp3e0DkgrCOsg.png" /></figure><p>Whereas this one is not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*FQFgyWt2Ni03AQF35QQcWQ.png" /></figure><p>There are many unit testing frameworks available for Ruby users, such as RSpec, MiniTest, and Cucumber. A new Ruby user, however, might want to avoid bringing in outside tools initially, and instead start out their unit testing exploration with Test::Unit, Ruby’s built-in framework. This is the framework we will demonstrate below.</p><p>Let us begin by creating a simple Ruby class, LiarLiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*vMmKImbb6i13hxxceuSIZA.png" /><figcaption>LiarLiar.rb Code</figcaption></figure><p>We COULD create a few LiarLiar objects and test some of their functions manually, as shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*iuN4J3_640xSACiBCZZq_A.png" /><figcaption>Sample LiarLiar.rb Code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*49NhqV9cYtAONl5ht_Cjlg.png" /><figcaption>Sample LiarLiar.rb Output</figcaption></figure><p>…but this method of error-detection can becoming quite time-consuming as a program grows in size and complexity. Instead, Test::Unit provides us with a way to test scenarios quickly and in bulk. To do this, we must create a new class, tc_LiarLiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*BkfPq_ymj62ekJ8D6oenzw.png" /><figcaption>tc_LiarLiar.rb Code</figcaption></figure><p>This new class inherits from Test::Unit::TestCase, and consists of various member functions, or test steps, that each evaluate a different part (unit) of the overall class. The “tc_(ItemTested)” naming convention used here is traditional, but not necessary. Each function contains one or more assertions which check whether or not a condition is satisfied by the unit under specific circumstances. If we already know the exact circumstances we wish to test, we can also define some additional member functions, setup and teardown, to run before and after each test; this saves time, since you no longer have to define a new object for each assertion, but is not required. When run, this tester will output the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*CgBYTfT5EYOjfKGWZQ1tUA.png" /><figcaption>tc_LiarLiar.rb Output</figcaption></figure><p>In each of the 6 tests, all assertions are checked for exceptions. In total, there are 9 assertions, 2 of which failed; here, these assertions were designed to fail, which is why their encompassing tests were named test_LiarPunishFailure and test_LiarCheckFailure, respectively. Each failure results in the output of a paragraph describing which test contains the faulty assertion, the assertion’s line number, and the expected value the assertion failed to obtain. Test::Unit also allows you to include error messages within your failure descriptions for easier debugging; here, test_LiarPunishFailure was assigned the message “Miscarriage of justice” while test_LiarCheckFailure was given none.</p><p>This demonstration included 2 assertion types, assert and assert_equal, but there are many other versions available to assess the performance of units in a variety of different areas. Some of these assertion types are listed below, alongside a short description of their respective purposes:</p><p>assert(true, “message”) — succeeds if the test returns true</p><p>assert(false, “message”) — succeeds if the test returns false</p><p>assert_equal(expected, actual, “message”) — succeeds if expected = actual</p><p>assert_not_equal(expected, actual, “message”) — succeeds if expected = actual</p><p>assert_nil(object, “message”) — succeeds if the object tested is nil (nonexistent)</p><p>assert_not_nil(object, “message”) — succeeds if the object tested exists</p><p>assert_match(pattern, string, “message”) — succeeds if string contains/is similar to pattern</p><p>assert_operator(A, operator, B, “message”) — succeeds if the operator comparison of objects A and B returns true</p><p>assert_no_match(pattern, string, “message”) — succeeds if string is dissimilar to pattern</p><p>assert_in_delta(floatExpected, floatActual, delta, “message”) — succeeds if floatActual is within delta of floatExpected</p><p>assert_instance_of(class, object, “message”) — succeeds if object is an instance of class</p><p>assert_kind_of(class, object, “message”) — succeeds if object.kind_of is true</p><p>assert_same(expected, actual, “message”) — succeeds if actual.equal?(expected) is true</p><p>assert_not_same(expected, actual, “message”) — succeeds if actual.equal?(expected) is false</p><p>assert_raise(exception A, exception B, …){block} — succeeds if the block raises one or more of the listed exceptions</p><p>assert_nothing_raised(exception A, exception B, …){block} — succeeds if the block fails to raise any of the listed exceptions (non-listed exceptions not considered)</p><p>assert_throws(symbol, “message”){block} — succeeds if the block throws the symbol</p><p>assert_nothing_thrown(symbol, “message”){block} — succeeds if the block throws the symbol</p><p>assert_respond_to(object, method, “message”) — succeeds if the object can respond to the method</p><p>assert_send(method, “message”) — succeeds if the method returns true when sent to the object</p><p>As mentioned previously, the individual member functions of test cases are also known as test steps, since they are the smallest functioning components of a test case. Our file contained only a single class/test case; however, just as test steps can contain multiple assertions, unit testing files can contain multiple test cases. Such files are called test suites, and are generally named “ts_(ItemTested)” in order to distinguish them from test cases. Like test cases, test suites can contain tests evaluating broad, indirectly-related portions of a program, or tests evaluating interlinked parts only (though the latter use is more efficient). Finally, while test suites are intended to run multiple test cases all at once, they can also run subsections of test cases, or only a single test case at a time.</p><p>Written by:</p><p>Christian Tith @cttith</p><p><a href="https://www.linkedin.com/in/christian-tith-43385816a/">https://www.linkedin.com/in/christian-tith-43385816a/</a></p><p>Sebastian Macedonio @semacedonio</p><p><a href="https://www.linkedin.com/in/semacedonio/">https://www.linkedin.com/in/semacedonio/</a></p><p>Sarah Fontenot <a href="https://medium.com/u/f5ce5260eb6d">@</a>sarahfontenot11</p><p>LinkedIn: <a href="https://www.linkedin.com/in/sarah-fontenot-43baa1168/">https://www.linkedin.com/in/sarah-fontenot-43baa1168/</a></p><p>Chuong Vu @cvu014</p><p><a href="https://www.linkedin.com/in/chuong-vu/">https://www.linkedin.com/in/chuong-vu/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ae8d19b4fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plp-ruby/ruby-debugging-and-testing-48ae8d19b4fc">Ruby: Debugging and Testing</a> was originally published in <a href="https://medium.com/plp-ruby">PLP Ruby</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby control/data abstractions, data types and structures , and expressions]]></title>
            <link>https://medium.com/plp-ruby/ruby-control-data-abstractions-data-types-and-structures-and-expressions-a49118b8656d?source=rss-4397185a838------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49118b8656d</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Christian Tith]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 09:31:13 GMT</pubDate>
            <atom:updated>2019-03-03T23:25:44.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ruby: Abstractions and Expressions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*77R10qOtgL9NyVHVGiZ45w.png" /></figure><h3>Data Types and Data Structures</h3><p>Data types in Ruby are actually objects. Ruby has the typical data types and data structures that are found in other languages, some with slightly different names. It contains Numbers, Strings, Booleans, Symbols(static identifiers), Arrays, and Hashes. We’ll run a few sample code snippets in Visual Studio Code to get familiar with the syntax and behavior.</p><p><strong><em>Numbers</em></strong></p><p>This is pretty self explanatory, a number is just like an int or float found in other programming languages. The behavior is like that of C++/Java, when mixing two types( int and float ), you’ll receive a float.</p><p>Let’s take a look at an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*tkYRD38dEuRs8SZW43yYfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*uw5DwasdFy-gR5Diqd57OA.png" /><figcaption>Int and float behavior</figcaption></figure><p><strong>Strings</strong></p><p>Strings in Ruby are quite simple and very easy to create. Any thing you’d want store in a string just requires you to enclose the information within quotes (“information”). Ruby creates an object for every string created, even if they contain the same information — this is different from Symbols as we’ll see soon enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*7cWaAKJhBHM2puIdO6SoFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*hRwATTGjNgSnSyoNhsWgdQ.png" /><figcaption>Printing a string</figcaption></figure><p><strong>Booleans</strong></p><p>Booleans in Ruby contain three values: true, false, and nil. Nil being “nothing”. They are commonly used as a flag to define the state of a program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*BVRtDaT9bbuzs33z9AzPdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*O9SVokgNs-QwaQIwi5v4dA.png" /><figcaption>Using booleans as flags</figcaption></figure><p><strong>Symbols</strong></p><p>Symbols in Ruby are kind of like Strings, but not entirely. They are static unique identifiers, they are used when we want to store a so-to-speak ‘code’. They are preceded with a ‘:’ and do not contain spaces. Only one identifier per code, this means that if you call print on the symbol, it will refer to the one that was previously created. These are quite useful when paired with a hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*KK88OBVQGoWl-52eh4r4Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*gItlZSfTof7n06U2vGINlg.png" /><figcaption>Printing symbol</figcaption></figure><p><strong>Arrays</strong></p><p>Arrays in Ruby are a collection of objects. They are created by putting brackets around comma-separated objects. Arrays are zero-based and they also keep the order of the objects from how it was constructed. However, elements can be added or replaced by indexing the array. We’re going to be showing you how to add elements, and replace elements. If trying to access an element that doesn’t exist, a nil will be returned. Arrays also have plenty of functions that can be applied on them, and with a little creativity can be very powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*enKGjc4l9OJ6nYl4XoVv2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*4Bu1dHAL3bMPsmW5yUknzg.png" /><figcaption>Replacing object in array</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*VnDRqcum5dlZgQEbmsnHxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*cq51SyLlyhu1gHkhIbBz8w.png" /><figcaption>Adding element to array</figcaption></figure><p><strong>Hashes</strong></p><p>Hashes is very similar to an array in that it can store many objects, the only difference here is that they are accessed by a key value. Entries into a hash are structured as a (key,value) pair. Just like a dictionary in Python or a HashMap in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eB5tKner5Yv9MkBrC7UhNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*y2Q7UNk4KiknRPlXzgePoQ.png" /></figure><h3>Data Abstraction</h3><p>Abstraction is the process of reducing a complex entity into a simplified representation of itself. In most programming scenarios, knowing exactly how the computer is managing every bit of data is unnecessary and difficult for humans to understand; to address this issue, high-level languages use data abstraction to conceal extraneous and irrelevant details about data implementation.</p><p>In computer science, data is any stored information. Data types, meanwhile, are categories of data defined by their membership and operation rules. For example, values belonging to a number data type are only allowed to take on numerical values (no letters!), and can be used in operations such as addition, subtraction, multiplication, division, and exponentiation.</p><p>One of the core principles of Ruby is that all data, whether simple units or extensive tables, should be represented via objects. This means that data types are classes, and any instance of some data type is an object belonging to that data type’s class. Additionally, the operations performable on these objects are encapsulated within its data type’s class as methods. For example, if I assert the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ilOFb1yxrdFojATl_QhBIQ.png" /></figure><p>Then I am declaring an object of the Ruby class Fixnum in the first line and invoking the * (multiplication) method of class Fixnum on objects a and 2 in the second.</p><p>Below are some of Ruby’s major data types (classes):</p><p>· Numeric — contains numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*hGmH-_58FyD8lP3KsswZhA.png" /></figure><p>· Integer — contains integers (whole numbers)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*A21tr3FS5iWNFs0eC_yupQ.png" /></figure><p>· Fixnum — contains small to medium sized integers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*eU9LtaOO9Z_LFN3wdMoICg.png" /></figure><p>· Bignum — contains large integers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*UNYwmyF_KxV4E-Niw1d1_w.png" /></figure><p>· Float — contains floats (decimal numbers)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*qai1Gid-Wchei1X2gSxAGA.png" /></figure><p>· Complex — contains complex numbers (numbers with imaginary components)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*vi3q7D8uFncoAoHqh1HBTA.png" /></figure><p>· Rational — contains rational numbers (fractions)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*nVSikaMrmQCXQYIIK8A_rw.png" /></figure><p>· BigDecimal — contains floats, but with better precision (which helps with rounding errors)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DDVRjJrQR05qDtr3UlErjg.png" /></figure><p>· String — contains strings, which represent variable values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*AmCsLPxtndh00UyQKy5Sog.png" /></figure><p>· Symbol — contains symbols, a data type specific to Ruby which are indicated by colons; unlike strings, they represent static values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*dEgByAb_mO2AbzfuPSKtTQ.png" /></figure><p>· Hash — contains hash tables, which function like dictionaries…they contain a list of values with corresponding keys for indirect access</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*7WnMqDAR1T-u8zxiAH3iEA.png" /></figure><p>· Array — contains arrays, which are like hash tables whose keys are simply the value’s position in the list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*bYh06jfJofiDcIeQTsu3hg.png" /></figure><p>· TrueClass — contains only the boolean value true</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*rSDl8VehMU3D2yW-QJpTcA.png" /></figure><p>· FalseClass — contains only the boolean value false</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*GFSvvADfrLgfJWvnPzjFjA.png" /></figure><p>· NilClass — contains only the nil (“nothing”) value, which indicates that nothing is stored in a location</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*hwmFXq9mDlpaUEejxrEDEg.png" /></figure><p>Note that some data types are subclasses of others; for example, objects contained within either the Integer class or Float class also belong to the Numeric superclass.</p><p>Outside of these built-in classes, Ruby programmers can also implement their own data abstractions by creating new classes. The basic format is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*FQ31owsidbxStAqaBXz_Yw.png" /></figure><h3>Control Abstraction</h3><p>While programming, you may find yourself oftentimes repeating actions in a pattern. Or maybe you will find yourself trying to give your program a branch of decisions. In these cases, look to control abstractions to simplify your program.</p><p><strong>Conditionals</strong></p><p>Sometimes, you need a program where if a condition is met, then you do a certain action, and if not, then you do a different action. To improve this process, we have conditional structures.</p><p>One of these conditional structures is the if block. In this example, we will be checking if a variable, ‘a’, is 2, then we want to print out that “a is equal to 2”. The if block will only execute if the conditional evaluates to true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*s_2-YzR9XZ4yjcfPNrSmMQ.png" /><figcaption>Example: If Conditional</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*cbPPYP1cZ2rS3mKlR6Lp7A.png" /><figcaption>Example: If Conditional Output</figcaption></figure><p>In this case, we first set the variable = 2. If ‘a’ is equivalent to 2, it puts the expected output message in. All conditional blocks must have a corresponding end keyword to end the conditional.<br>To expand this, we can use the else/elsif blocks. With the elsif block, it is used when we must cover a singular option that is separate from the if block. There can be multiple elsif blocks corresponding to an if block. The else block is used for covering any other options except those covered in the elsif and if blocks. Every single elsif and else block MUST correspond to a single if block, and cannot stand on its own. If multiple blocks evaluate to true, the program will utilize the first block that it encounters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*I-wFNdImHtPrMairB1HaFw.png" /><figcaption>Example: If/elsif/else conditional blocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*QypXya3sNEAPq_aIDESH2A.png" /><figcaption>Since a is set equal to 3 at the beginning of the program, it will print what is in the elsif block because it is the first condition to match</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*LbvedU6Ex-Br7t9iSeFCpA.png" /><figcaption>Example: If/elsif/else conditional blocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*muglOaiMqH8qR6DzoX6dHw.png" /><figcaption>Since a is equal to 100, it evaluates each of the conditionals one by one, until it finally reaches the else block, where it prints “a is not 2 and not 3”</figcaption></figure><p>Opposite of the if statement, we can utilize the “unless” statement. Unlike the if statement, the code within the “unless” block will only execute if the condition evaluates to false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*M-j07Sv-8uGFE90nO02-4A.png" /><figcaption>Example: Unless Statement</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ACf6xs_u_oKxk6kEB61xMg.png" /><figcaption>In this case, the code, since a is not equal to 2, will read whatever is inside the unless block and output that it reaches. The only way it will not reach is if a = 2 before the unless statement.</figcaption></figure><p><strong>Loops</strong></p><p>Loops refer to repetitive execution of code until a condition is met. We can start with a simple loop to demonstrate the concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*x42bQHAmo8qd6cDp4u7XPw.png" /><figcaption>Example: Simple Loop</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTJwmEeLCdvjhBl0bo0wFA.png" /><figcaption>Example: Simple Loop Output</figcaption></figure><p>We start with the keyword ‘loop do’ and within this control structure, we output testing in order to test our looping. Finally, when we are finished with our loop structure, we use the ‘end’ keyword to signify this. This end keyword will be utilized throughout for the control structures to signify that we are finished. As you can see, since we do not specify a condition to end it, it runs into what is known as an “infinite loop”, where the action just keeps repeating.<br>We can fix this by utilizing the ‘break’ keyword. Let’s say that we want to break if we output it 4 times. We can keep track of this by utilizing a counter and incrementing it every cycle and breaking if it reaches 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*2gqle2iS3VC1HQib7pAZbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*cukJVou1y7CjWtbNHmjimg.png" /></figure><p>Let’s say we don’t want to use this ‘break’ keyword, and instead want to be clearer on conditionals, but still loop. Another type of loop we can use is the while loop.</p><p>Typically, while loops are used when you you want to repeat an action until a certain condition is met. For example, lets say we want to output the numbers from 0–10. In this case we want to keep repeating the output, however increment it by 2 at every “loop”. By doing this, the condition will be met once it reaches 12, because you are incrementing it by 2 every time, and the loop will end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-U7aR829XIleuqaVaxau8g.png" /><figcaption>Example: While Loop</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZdttH0HQZYvJHuN4HYfqw.png" /><figcaption>Example: While Loop output</figcaption></figure><p>In extension to the while loop, there also exists a for loop. Deciding when to use the for loop and when to use a while loop is up to you. Personally, it is easier to use for loops when you know the bounds of your conditions, while loops when you are not sure when it ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*tlWdKm2ByJ3YYQuxhXmUow.png" /><figcaption>Example: For Loop</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3Yg9q8yHqdZor5YPd9vSQ.png" /><figcaption>Example: For Loop Output</figcaption></figure><p>In the for loop, you specify the range using whatever number you start with, in this case 1, and then “..” and then the end range. This range is inclusive on both ends, including both the upper and lower bounds.</p><p><strong>Subroutines</strong></p><p>Say you want to compartmentalize your code so that it can be called anywhere in the program with just a simple line of code, instead of a huge block of code. To do this, you would want to utilize a Ruby feature known as a subroutine. Subroutines are known by a couple different names. For now, we will refer to them as methods. In other languages, they may be referred to as functions. In this case, the methods of Ruby always begin with the “def” keyword, whatever code you want to be encapsulated in the function, and the end keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*J6Sl2cktUeR7m6f4NX96Zw.png" /><figcaption>Example: Subroutine that returns the name variable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*y8rj6UrdTDLY_0QEJGvHsg.png" /><figcaption>Output for subroutines code pasted above; Calls the subroutine sayMyName and returns name.</figcaption></figure><p>If you need to pass in variables from the program into the method, there is an option for that. By using parameters, we can pass in variables to manipulate/use inside our subroutine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*r77LX8s90n8vxW0GJpGd7A.png" /><figcaption>Example: Subroutine with Parameters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*9te9KVLqjeoSbGzvjcMnoA.png" /><figcaption>Executes the code above. It takes the parameter passed inside and adds string to the newName and returns it as a string value. It then prints it.</figcaption></figure><h3>Expressions</h3><p><strong>Assignments</strong></p><p>Assignments in Ruby are like most programming languages, you assign a variable a value from the right hand side of the ‘=’ sign.</p><p>In this example below, Ruby has a useful feature where you can multitask by calculating and assigning values to variables at the same time all in one continuous expression. If you like, you can do this with a mix of decimal number and it will calculate and assign the numbers expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Euvy2zufkRBdwVjBxZ21xw.png" /></figure><p>Another form of multitasking as assigning variables with expressions. Variable X stored an integer number, while Y stored a decimal number, another example of using just one decimal number to output a decimal value. Finally variable Z used the values stored in X and Y in its expression. At this point the values of X and Y are already defined and it’s ok to use them within the same line of assignment as longs as those variables get assigned first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*pIb84GWVFj6EoslwKh4SFQ.png" /></figure><p><strong>Numerical Expressions</strong></p><p>In this example below, you can assign multiple variables at the same time with a number, can be an integer, such as the example, or a double value such as 12.0 to be consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*dXRbEzjCC0J1MVPMq7nytw.png" /></figure><p>If you’re dealing with calculations that you would expect results as decimals or even inputs as decimals you would have to write the numeric expressions with at least a number left and a number right of the decimal place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*svVUjn00Iy1htanAiPeIgQ.png" /></figure><p>As you can see from this example, there’s an error with calculating a decimal number with no digit to the left of the decimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AwvsmFc1DhvZhix8grffQ.png" /></figure><p>One thing that Ruby lacks are the increment and decrement by one operators. Sure you can add a ‘++’ or ‘- -‘ but it produces different results. Using ‘++’ would be equal to a+a instead of a+1. If using a- — it would be equal to a-a;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*yo8d7OJr27XDa0Qm6MQiwg.png" /></figure><p><strong>String Expressions</strong></p><p>You can concatenate strings on the fly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Oa4TluM9CZlY1N0iI5yEww.png" /></figure><p>This works with a combination of strings and variables that contain strings as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Bk5AfGRUD5h3gZ4zU6QMeA.png" /></figure><p>You can have a complex expressions within an argument such as an if statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*EfKJsply3vgfWfcROEvWoQ.png" /></figure><p><strong>Logical Expressions</strong></p><p>For logical expressions you can compose statements with the &amp;&amp; an || operators as shown below. The expression can be written in many different ways such as ((12–8)/9-z) != z or ((12–8)/9-z) &lt;= z and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*IzNGDI1lpPI03k0gmGYSng.png" /></figure><p><strong>Operator Precedence</strong></p><p>When writing an expression you would have to consider precedence. In math there exist the acronym PEMDAS, which stands for the precedence of operators in math expressions.</p><p>The precedence of operators are as follows</p><ul><li>[] or ()</li><li>** (exponentiation)</li><li>! ~ +- (unary plus and minus)</li><li>* / %</li><li>&gt;&gt; &lt;&lt; (right and left bitwise shift)</li><li>&amp; (bitwise AND)</li><li>^ | (bitwise XOR and OR)</li><li>&lt;= &lt; &gt; =&gt; (comparison operators)</li></ul><p>Written by:</p><p>Christian Tith @cttith</p><p><a href="https://www.linkedin.com/in/christian-tith-43385816a/">https://www.linkedin.com/in/christian-tith-43385816a/</a></p><p>Sebastian Macedonio @semacedonio</p><p><a href="https://www.linkedin.com/in/semacedonio/">https://www.linkedin.com/in/semacedonio/</a></p><p>Sarah Fontenot <a href="https://medium.com/u/f5ce5260eb6d">@</a>sarahfontenot11</p><p>LinkedIn: <a href="https://www.linkedin.com/in/sarah-fontenot-43baa1168/">https://www.linkedin.com/in/sarah-fontenot-43baa1168/</a></p><p>Chuong Vu @cvu014</p><p><a href="https://www.linkedin.com/in/chuong-vu/">https://www.linkedin.com/in/chuong-vu/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49118b8656d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plp-ruby/ruby-control-data-abstractions-data-types-and-structures-and-expressions-a49118b8656d">Ruby control/data abstractions, data types and structures , and expressions</a> was originally published in <a href="https://medium.com/plp-ruby">PLP Ruby</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby for Beginners, written by beginners!]]></title>
            <link>https://medium.com/plp-ruby/ruby-for-beginners-written-by-beginners-4949e127e32a?source=rss-4397185a838------2</link>
            <guid isPermaLink="false">https://medium.com/p/4949e127e32a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Christian Tith]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 05:32:59 GMT</pubDate>
            <atom:updated>2019-02-18T14:53:11.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ruby For Beginners, By Beginners!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*nV_D4YP8y1QiCsiE.png" /></figure><p>Ruby is an interpreted object-oriented programming language built to support multiple programming paradigms. It was originally designed to be as general-purpose a scripting language as possible, which has allowed it to grow into a tool that provides support for a large variety of different applications. These days, Ruby is most frequently used for web applications, standard libraries, servers, and other system utilities.</p><h3>Installation on Windows</h3><p>To install Ruby on Windows go to: <a href="https://rubyinstaller.org/">https://rubyinstaller.org</a> and select the Ruby installation corresponding to your version of Windows. There are multiple different software bundles to choose from. Opening the installer and following the installation instructions will install Interactive Ruby as well, which we’ll talk about soon. Pictured below is the primary installation screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7qJRI88K5jBy7QudK_e7g.png" /></figure><p>The selection that is given is optional, other bash shells, in this case we’ll be using CMV. After making your selection, search and open “Interactive Ruby” on the Start Menu search bar. Another way is to open CMD and enter “irb” and it will open it as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*VvPQ-fE3dOlsTVgB-hvscg.png" /></figure><p>You’ll know it has activated when you see the following result when searching for “irb”. Apart from its utility in installation, Interactive Ruby is a great tool for exploring the Ruby language; we’ll be using it to build our first program!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*lA9AU9cjQESfVyxFh_5tIw.png" /></figure><h3>Installation on Linux</h3><p>To install Ruby on Linux you can go to <a href="https://www.ruby-lang.org/en/documentation/installation/">https://www.ruby-lang.org/en/documentation/installation/</a>, where there is step-by-step instructions for running commands to the Terminal for installation based on your specific OS. After installation you’ll be greeted just as the Window’s version of installation. To open Interactive Ruby simply open Terminal and enter “irb” and to start. Now that interactive ruby is open, both Windows and Linux instructions will be the same.</p><h3>Package Management with RubyGems</h3><p>To improve your Ruby programming experience, it is important that you now find a way to streamline your package usage. In brief, packages are collections of software which can be more efficiently handled (downloaded, edited, removed, etc.) via package management systems, better known as package managers. Ruby users have access to a variety of options when it comes to package management; however, the best known Ruby package manager is RubyGems, which can be downloaded here for free: <a href="https://rubygems.org/pages/download">https://rubygems.org/pages/download</a>.</p><p>The front-end script for RubyGems is a command line tool called <em>gem</em>, which you can use to install, update, and delete Ruby packages colloquially known as “gems”. Below are the commands and subcommands most useful for beginners learning to operate <em>gem</em>:</p><p>gem install (x) — this installs a gem; the gem name is specified in the location placeheld by (x)</p><p>gem environment — this displays your RubyGems configuration information</p><p>gem list — this generates a list of every gem you have installed</p><p>gem update (x) — this updates a gem; the gem name is specified in the location placeheld by (x)</p><p>gem update — this updates all installed gems</p><p>gem update — — system — this updates RubyGems itself</p><p>gem uninstall (x) — this deletes an installed gem; the gem name is specified in the location placeheld by (x)</p><p>As is the case with most package managers, one of RubyGems’ perks is its ability to download gems independently to optimize your experience without unnecessary user input, which is particularly useful for resolving package dependencies. For example, say you install a gem backtap which relies on another gem frontpat; instead of forcing you to manually request both gems or breaking down when backtap is used without frontpat present down the line, RubyGems automatically checks for any dependencies in backtap and installs both gems.</p><p>As a new Ruby user, you should ideally be running the most recent version of Ruby; if you are not, and are instead operating Ruby 1.8 or earlier, then your Ruby package management experience will have a few extra steps. Specifically, you will have to preface your use of any installed packages with the command below:</p><p>require ‘rubygems’</p><p>This loads in the rubygems module and allows your program to access any gems you have installed in the past. Thankfully, this step is no longer necessary when using any Ruby version past and including Ruby 1.9.</p><p>Finally, do not be afraid to turn to <em>gem </em>itself if you need any more help, since RubyGems is self-documenting and therefore comes with its own instruction manual. To access this information, type “gem help” in the command line; alternatively, you can access a more complete version of RubyGems’ documentation at <a href="https://rubygems.org/">https://rubygems.org</a>.</p><h3>Writing our first program!</h3><p>This wouldn’t be a beginner tutorial unless we included a step-by-step on how to create a “Hello World!” program!</p><p>To get started we’re going to be opening up the Interactive Ruby Console we downloaded from the installation step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCdu58sNUGurQlgDzAXyhw.png" /><figcaption>The magical black box!</figcaption></figure><p>So for our first program we’re going to be creating a method that will print “Hello World!”. To get started we have to understand what is going on with our console. You’ve probably noticed the “irb(main):001:0&gt;” when opening up the console. If you’re new to programming this might seem a bit archaic, and if this isn’t your first time it may be very familiar. Regardless, we’re going to explain it to dispel any doubts. As you might have guessed, “irb” stands for Interactive Ruby. “main” is going to be our driving program, this is where we want to put our code. The following numbers represent the line number of our current program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8l3iqTdM6T4ydbU9BMUuXQ.png" /><figcaption>Defining our method</figcaption></figure><p>Now comes the fun part, programming. To begin we are going to need to type “def” this is a keyword that will let the console know that we are going to be creating a method/function. Following “def” should be the name of our method, in this case we’ll call it “HelloWorld”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pDpl4CGjM5J_YG_c2zS5Q.png" /><figcaption>Inserting a print statement</figcaption></figure><p>In Ruby to print a statement, we use the “puts” keyword, followed by our sentence in quotes. Now that we have put the desired output in our method, we need to let the console know that we’re done. To do so we need to include the “end” keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWyus5BLy11T7FLdbkisPg.png" /><figcaption>Finishing up our method</figcaption></figure><p><em>This will return a “=&gt; :HelloWorld”, signifying that our function HelloWorld has been defined and is now able to be called. We can now call our function by calling the method and including a set of parentheses.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-81njunLcrkoc0_KhT7HvA.png" /><figcaption>Calling the method</figcaption></figure><p>Now to call our function we just type out the name of it, followed by “()”. As you can see it prints to the console “Hello World!” followed by “=&gt; nil”. This arrow and nil is the return type of the program. Which in our case the method returns nothing.</p><p>Congratulations! You’ve just written your first program in Ruby. Not too bad huh? We’ll get deeper into the language as we learn much more. For now enjoy the greatness that is Ruby and try creating some other programs.</p><p>Happy coding, and good luck!</p><p>Written by:</p><p>Christian Tith @cttith</p><p><a href="https://www.linkedin.com/in/christian-tith-43385816a/">https://www.linkedin.com/in/christian-tith-43385816a/</a></p><p>Sebastian Macedonio @semacedonio</p><p>-</p><p>Sarah Fontenot <a href="https://medium.com/u/f5ce5260eb6d">@</a>sarahfontenot11</p><p>LinkedIn: <a href="https://www.linkedin.com/in/sarah-fontenot-43baa1168/">https://www.linkedin.com/in/sarah-fontenot-43baa1168/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4949e127e32a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plp-ruby/ruby-for-beginners-written-by-beginners-4949e127e32a">Ruby for Beginners, written by beginners!</a> was originally published in <a href="https://medium.com/plp-ruby">PLP Ruby</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>