<?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 Kristen Fletcher Wilde on Medium]]></title>
        <description><![CDATA[Stories by Kristen Fletcher Wilde on Medium]]></description>
        <link>https://medium.com/@kristenfletcherwilde?source=rss-f582634ec512------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hveSuY_Lgof5v5tDPhBV6w.png</url>
            <title>Stories by Kristen Fletcher Wilde on Medium</title>
            <link>https://medium.com/@kristenfletcherwilde?source=rss-f582634ec512------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:29:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kristenfletcherwilde/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[Building Subtract.Online]]></title>
            <link>https://medium.com/@kristenfletcherwilde/building-subtract-online-8db236689bb8?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/8db236689bb8</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[agile-development]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 17:33:59 GMT</pubDate>
            <atom:updated>2018-06-11T01:25:58.663Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: I drafted this post around May 7–9, 2018, as I was beginning to design this project. The publication date says June 8 because that’s when I decided to share it. I don’t expect readers to be interested in every detail presented here; many of my initial plans have changed and evolved anyway. This is just an outline of the general process that I followed in the early stages of planning. I’d be thrilled to talk with anyone about the process and/or the app!</p><h3>Introduction</h3><p>I am embarking on a project which will provide me a chance to practice building a web app with Rails 5.1 and Vue.js. The finished product will be a math review tool for my daughter who is currently finishing up first grade.</p><p>I’m designing this project from scratch, and I’d like to take this opportunity to briefly write out each step of the Agile process I’m following. These steps are from Launch School’s free online book, <a href="https://launchschool.com/books/agile_planning/read/writing_scenarios">Agile Planning</a>.</p><h3>Personas</h3><p>I’ll call my user Jennifer. She’s 7 years old, finishing up first grade, and this year she’s learned a lot about addition and subtraction of whole numbers up to 20. Her teacher has encouraged the students to use a specific website where they are given 6 seconds to answer each math question. Jennifer finds this very stressful and she avoids it as much as possible. It’s easy when she already knows the answer, but if not, 6 seconds is not enough time for her to figure it out.</p><h3>Scenarios</h3><ol><li>Practicing. The app presents Jennifer with a math problem and then allows her as much time as she needs to figure it out. There could be a UI where she can manipulate elements to find her answers. She practices for a reasonable amount of time, then the session ends.</li><li>Keeping data. The app remembers math facts Jennifer has practiced before. It keeps track of the time it takes her to answer a problem during a session.</li><li>Viewing progress. The app can display a list/chart of the problems Jennifer can answer in 5 seconds.</li><li>Signing up. Jennifer’s mother navigates to our web app, signs Jennifer up, and adds a shortcut to her tablet. (For simplicity, our app doesn’t require email validation, just a unique username. It will attempt to safeguard children’s privacy by not collecting or sharing sensitive information.)</li><li>Logging in and out. Staying logged in with cookies is not necessary. There is a log in/log out button.</li><li>Incentivizing/motivating. Jennifer wants to practice because there is a reward involved.</li></ol><h3>The Core</h3><p>The core of this app is practicing math facts.</p><h3>Wireframing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*qr70Ja_mNADdKfKdYibn-g.png" /><figcaption>Wireframe idea: before practice</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*uKdpPEP6omaCP3Q8lsn-AQ.png" /><figcaption>Wireframe idea: during practice. If a student takes a long time to solve a problem, also ask the related addition fact (5 + 6 in this case), with a signal that this is addition (flashing ‘+’ maybe).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*iXg8m2t4cYyeaiDBsnpzxA.png" /><figcaption>Wireframe idea: after practice</figcaption></figure><h3>Prioritized/ordered backlog of stories broken down from epics:</h3><p>Starting with epics and breaking them down to stories was an incredibly useful process!! There were all sorts of features I thought of for this project, and I knew I needed to narrow them down but I had a hard time giving up some of the features that seemed “cool”. Thinking empathetically about what my user would actually want <em>and why</em> as she attempted to meet her own goals proved to be the key!</p><p>I was happy to realize that I don’t have to start with the landing page/sign up/log in. Of course those things will be essential but there are good reasons to start with the core functionality. Most importantly, I can have actual users test it and give feedback.</p><p>I am also enjoying the experience of seeing details get ‘fleshed out’ or ‘broken down’ bit by bit. As I began to conceptualize this app, I had a few ideas that I wanted to incorporate but hadn’t quite articulated, even to myself. As I worked on breaking down the stories into finer, testable bits of functionality, this happened very naturally. For example, ‘As a child, I want math problems to be presented in a progressive order of difficulty so that it doesn’t feel overwhelming’ got broken down into stories related to the concept of ‘mastery’. As I wrote tests, ideas about implementation started creeping in. I decided to jot them down, with the understanding that the implementation could change.</p><p>Here are the stories I plan to start with, in an order that makes sense. Acceptance tests in <em>italics </em>follow each story.</p><p>As a child user, I want to see the math facts I’ll be working on next and those I’ve mastered so that I have a sense of progress. | <em>A starting view will display the problems, a brief explanation, and a way to start (ie start button). Problems can be generated by the program but each problem should have a unique identifier.</em></p><p>As a child I want a clean, attractive UI for solving problems so that I can stay focused. | <em>A practice view will present the problem and a text input (number) for the answer. When a correct answer is typed in, the view responds immediately.</em></p><p>As a child I want an incorrect answer to be acknowledged if I press enter, but I want a chance to try again. | <em>If an incorrect answer is typed in and enter is pressed, the program displays “Try again.”</em></p><p>As a child I want the math facts to be presented to me in a progressive sequence so that the experience doesn’t feel too difficult. | <em>An array of a working problems is built from the first n problems (8–10?) that have not yet been mastered. They are shuffled and presented.</em></p><p>As a child I want to be able to ‘master’ problems so that I can move on to more challenging ones. | <em>When a problem has been answered correctly within 5 seconds two times, mark it ‘mastered’.</em></p><p>As a child I want ‘mastered’ problems to be occasionally reviewed so that I don’t forget them. | <em>Select a ‘mastered’ problems to include in the set of practice problems for each period.</em></p><p>As a child I want practice periods that are not too long (3–5 min?), so that I can focus but not get too tired. | <em>When a practice period begins, a timer is started.( 4 min for now, and then test with children.) After that time, the period ends when the current problem is answered correctly.</em></p><p>As a child I want to see how I did after each period so that I get feedback.</p><p>As a child I want some manipulative elements to fade in after about 5 seconds of looking at a problem, or after an incorrect answer, so that I have a way to solve it.</p><p>As a child I want to be able to select additional facts to practice so that I can move faster if I want to (I might want to avoid being bored / impress my parent / get this done).</p><p>As I child I want a navigation bar with links to the starting screen and to my account, so that I always know where to find these things.</p><p>As a child I want to be able to log in and log out so that I can access my own data and protect it from others</p><p>As a child I want an easy-to-use home screen directing me to log in or sign up so that I can use the app easily.</p><p>As a parent I want the home screen to briefly explain what this app is so that I can decide if I’m interested.</p><p>As a parent I want a privacy policy linked the home screen so that I feel I can trust this app.</p><p>As a parent I want tips on the home screen so that I will succeed in helping my child practice math (pinning to a device, rewards for practicing, write password)</p><p>As a child I want to access a table of my daily time and accomplishments so that I can demonstrate my progress and perhaps earn rewards from my parent.</p><p>As a child I want rewarding transition animations between problems so that I get immediate reinforcement for my work.</p><h4>Extra features to possibly add later:</h4><p>As a child/parent I want password recovery so that I can still use the app if I forget my password (requires adding parent email to account registration, and some way of adding a parent email to current user accounts)</p><p>As a parent I want to receive an email when my child signs up so that I can approve the use of the app</p><p>As a parent I want the option to withhold my consent so that I have control over my child’s internet use</p><p>As a child I want my first name to be used so that the app seems more personal.</p><p>As I child/parent I want more math problems to be added so that I can keep progressing</p><h3>Implementation: Creating ‘Issues’</h3><p>User stories and acceptance tests are the last things explained in the Agile Planning book, although it does mention that for larger teams, <em>sprints</em> and <em>releases</em> and <em>size estimation</em> might be needed. For my purposes, I feel that I need to do something to translate these stories, which are units of user value, into manageable tasks I can work on. Knowing that I plan to use Rails and Vue.js, I’m going to make a rough outline of the routes, controllers, models, and views that I’ll need, for the sake of having a mental model. Here we go:</p><p>Views: practice, login/signup/root, account. The practice view will basically hold a 1-page app where Vue will do most of the work.</p><p>Models: I’ll need a Users model with username and password_digest (strings). Each user will also have a problem set. Each problem will have a minuend (number), subtrahend (number) and some way of keeping track of how many times it’s been answered in 5 seconds or less. A mastered (boolean)? A success_times (number), where if it’s 2 it’s considered “mastered” by the front end, and if it’s 4 it won’t be reviewed any more? I think I like that. I’m realizing that I probably don’t actually want a model for individual problems because they aren’t going to be updated individually in the database with separate http requests. I just want to submit one request at the end of each practice period. Eventually I’ll also want a DatedRecords model with a one:many association with each user, which will have a date (datetime), minutes (number), problems_answered (number), and facts_mastered (number).</p><p>Routes and Controllers: I know I’ll need some CRUD actions such as get users#new and post users for signup, get session#new and post sessions for login, delete session for logout. I’ll try getting started with get users/:id for my practice view (alias get username), and patch users/:id to save the data with ajax at the end of each period (then render users/:id). Get user/:id/date_records/index (alias get username/account) could be the account page where the time summary of DateRecords is kept.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8db236689bb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving/Retrieving Data With a YAML file in Ruby: The Basics]]></title>
            <link>https://medium.com/@kristenfletcherwilde/saving-retrieving-data-with-a-yaml-file-in-ruby-the-basics-e45232903d94?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45232903d94</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Wed, 15 Feb 2017 19:18:23 GMT</pubDate>
            <atom:updated>2017-02-15T19:18:23.477Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing and reading yaml files can be very simple. Here are a few examples.</p><p>Writing an array to a yaml file:</p><pre>require &#39;yaml&#39;</pre><pre>pets = [&quot;dog&quot;, &quot;cat&quot;, &quot;hamster&quot;]<br>File.open(&quot;pets.yml&quot;, &quot;w&quot;) { |file| file.write(pets.to_yaml) }</pre><p>Retrieving the array:</p><pre>require &#39;yaml&#39;</pre><pre>pet_array = YAML.load(File.read(&quot;pets.yml&quot;))</pre><pre>p pet_array       <br>#=&gt; [&quot;dog&quot;, &quot;cat&quot;, &quot;hamster&quot;]</pre><p>See?! If, out of curiosity, you wanted to look at pets.yml, here’s what you’d see:</p><pre>---<br>- dog<br>- cat<br>- hamster</pre><p>Working with a more complex data structure is no different. Here is a recipe in the form of a hash which contains an array which contains some hashes.</p><pre>require &#39;yaml&#39;</pre><pre>recipe = { title: &quot;Coffee&quot;, <br>           ingredients: [ { ingredient_name: &quot;Water&quot;, <br>                            quantity: 8,<br>                            unit_of_measurement: &quot;oz&quot; },<br>                          { ingredient_name: &quot;Coffee Grounds&quot;, <br>                            quantity: 1,<br>                            unit_of_measurement: &quot;tbsp&quot; } ],<br>           directions: &quot;Make coffee.&quot;  }</pre><pre>File.open(&quot;coffee.yml&quot;, &quot;w&quot;) { |file| file.write(recipe.to_yaml) }</pre><p>Inside the yaml file:</p><pre>---<br>:title: Coffee<br>:ingredients:<br>- :ingredient_name: Water<br>  :quantity: 8<br>  :unit_of_measurement: oz<br>- :ingredient_name: Coffee Grounds<br>  :quantity: 1<br>  :unit_of_measurement: tbsp<br>:directions: Make coffee.</pre><p>Retrieving the file returns a new recipe hash populated with data equal to the data we saved.</p><pre>recipe_from_yaml_file = YAML.load(File.read(&quot;coffee.yml&quot;))</pre><p>And off you go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45232903d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on working with blocks]]></title>
            <link>https://medium.com/@kristenfletcherwilde/notes-on-working-with-blocks-6f12f4fc95a9?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f12f4fc95a9</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Mon, 16 Jan 2017 21:28:32 GMT</pubDate>
            <atom:updated>2017-01-17T19:59:55.642Z</atom:updated>
            <content:encoded><![CDATA[<p>Blocks are one way Ruby uses closures. A closure is a way to pass around an unnamed chunk of code.</p><p>Any method can take a block. When not given a variable in the method implementation, the block is an ‘implicit’ parameter. It relies on the keyword yield to be executed, otherwise it is ignored. If a method includes yield but is not given a block in the invocation, LocalJumpError is thrown. To write a method where a block is optional, use if Kernel#block_given?.</p><p>If a variable representing the block is desired for the method implementation, this can be done by prefixing &amp; to the variable name (only on the first line of the definition, where variables are initialized). This local variable is called an ‘explicit block parameter’, and converts the block into a Proc object. Instead of yield, use .call to call the block.</p><p><em>Arity </em>refers to the rules enforcing the number of arguments that can be called. Blocks have lenient arity rules; they don’t enforce argument count like normal methods in Ruby. Extra parameters are ignored, and absent parameters are given ‘nil’.</p><p>When to use blocks when writing methods: 1. To write flexible methods. A generic action is implemented; the specifics are decided upon when the method is invoked. select is an example of this. 2. Sandwich methods, which perform some actions before and after doing something. For example, a method which times how long it takes to execute any block could set a Time.now before and after executing it. Another example is File::open. When invoked without a block, the program must .close the file after writing. When invoked with a block that writes the file, File::open automatically closes the file after writing.</p><pre>File.open(&quot;filename.txt&quot;, &quot;permission&quot;) do |file| <br>  file.write(&quot;Stuff&quot;)<br>end</pre><h3>Procs and binding</h3><p>A Proc object keeps track of its surrounding context, including local variables, constants, method references, etc.</p><pre>def call_me(some_code)<br>  some_code.call <br>end</pre><pre>chunk_of_code = Proc.new {puts “hi #{name}”} <br>name = “Karen”</pre><pre>call_me(chunk_of_code)</pre><p>Because of its binding, the code above prints hi Karen even though only the proc (not the local variable name) is specifically passed into the method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f12f4fc95a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Happy New Year! Back to work.]]></title>
            <link>https://medium.com/@kristenfletcherwilde/happy-new-year-back-to-work-1ade413b4872?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ade413b4872</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[launch-school]]></category>
            <category><![CDATA[christmas]]></category>
            <category><![CDATA[parenting]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Wed, 04 Jan 2017 19:04:48 GMT</pubDate>
            <atom:updated>2017-01-04T19:04:48.289Z</atom:updated>
            <content:encoded><![CDATA[<p>Every so often I hear about parents who are able to do coding or other focused grown-up work while staying home with their children. And it blows my mind. I can hardly get through a household chore without one of my kids demanding my attention. Seriously. So, while they were out of school for two weeks for winter vacation I took a break from Launch School work, to pick up after — er, enjoy my children, and holiday stuff. I know, I could’ve taught them to be more independent, so I could do what I need to do. Are you judging my parenting? So am I. Let’s stop it, okay? :)</p><p>So, today I tried to get back into studying programming. It was hard to get started, and hard to pick up where I left off. And that was discouraging. But I set a timer, and made myself stay focused until things started coming back. And they did. And I’m so glad!</p><p>Now back to work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ade413b4872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby Regex Reference]]></title>
            <link>https://medium.com/@kristenfletcherwilde/cheat-sheet-for-regex-in-ruby-6f6360035545?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f6360035545</guid>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Fri, 04 Nov 2016 16:17:39 GMT</pubDate>
            <atom:updated>2016-11-08T17:54:24.626Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing Regular Expressions:</h3><p>/ Pattern start and end<br>[ ] character set or range, such as [aeiou] or [a-z]<br>| or, <br>&amp;&amp; and<br>^ not<br><strong>Characters:</strong><br>\w any wordlike character (alphanumeric or _ )<br>\d any digit 0–9<br>\s whitespace<br>\W any non-wordlike character<br>\D any character that is not a digit<br>\S anything except whitespace<br>. any character except newline <br>, literal comma<br>\. literal period<br>\+ literal “+”<br><strong>Repetition:</strong><br>+ one or more times<br>* 0 or more times.<br>? 0 or 1 times (optional)<br>{2} exactly two times<br>{1,3} minimum of 1 time, maximum of 3 times.<br>{3,} 3 or more times<br>{,4} 4 or less times<br><strong>Anchors:</strong><br>\b match between spaces or a period<br>\A start the match at the start of the string<br>\Z end the match at the end of the string<br>^ start matching after a newline<br>$ stop matching before a newline<br>\G start at the point where last match finished<br><strong>Grouping:</strong><br>( ) group characters together and capture (return) the groups<br>(?: group only for evaluating, not to be returned.<br><strong>Modifiers after the pattern:</strong><br>i makes the match case insensitive<br>m makes the dot . match newlines<br>x tells Ruby to ignore whitespace between regex tokens<br>o causes any { } substitutions to be performed just once, not every time.</p><h3>Methods:</h3><p><strong>the =~ operator</strong></p><p>Use on a string to match a regex, or on a regex (literal or in a variable) to match a string. Returns the integer position where the match started or nil.</p><p><strong>.match</strong></p><p>Can also be used on a string to match a regex or on a regex to match a string. Returns a matchdata object or nil, which can be used as boolean true or false.</p><p><strong>String#gsub and #gsub!</strong></p><p>search and replace with two parameters: (regex to search, replacement string) . The replacement string can include \0 to re-insert the regex match, or \1, \2, \3, etc for the capture groups.</p><p><strong>String#sub and #sub!</strong></p><p>searches and replaces just the first occurrence of a match.</p><p><strong>String#scan</strong></p><ul><li>.scan(/regex/)→ array</li><li>scan(/regex/){|match, …| block } → str</li></ul><p><strong>String#split</strong>(/regex delimiter/ =whitespace, optional_limit) → array</p><p>While scan puts each match of the regex pattern into an array, split puts each part of the string <em>between</em> matches into an array.</p><p><strong>Others</strong></p><ul><li>.index(regexp,[offset])</li><li>.rindex,</li><li>.partition</li><li>.rpartition</li></ul><h3>The MatchData object</h3><p>can be accessed with special global variables:</p><p>$~ holds the last MatchData object created</p><p>$&amp; holds the text matched by the whole regular expression.</p><p>$1, $2, etc. hold the text matched by the capture groups (first, second, etc.)</p><p>$+ holds the text matched by the highest-numbered capture group in the match.</p><p>$backtick holds the text to the left of the match.</p><p>$&#39; holds the text to the right of the match.</p><h3>Testing Ruby Regex’s</h3><p>Use <a href="http://rubular.com/">rubular.com</a></p><p>Information from <a href="http://www.regular-expressions.info/ruby.html">http://www.regular-expressions.info/ruby.html</a>, <a href="http://rubylearning.com/satishtalim/ruby_regular_expressions.html">http://rubylearning.com/satishtalim/ruby_regular_expressions.html</a>, and of course <a href="http://ruby-doc.org/core-2.3.0/Regexp.html">http://ruby-doc.org/core-2.3.0/Regexp.html</a>, which contains even more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f6360035545" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Little Ruby tricks]]></title>
            <link>https://medium.com/@kristenfletcherwilde/little-ruby-tricks-ee4907b9fd51?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee4907b9fd51</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Fri, 28 Oct 2016 20:55:49 GMT</pubDate>
            <atom:updated>2017-01-17T20:12:47.002Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working on a lot of small problems for practice over the last week, and come across several little tips and tricks I’d like to remember. Mostly just methods and ways of writing syntax. Until all this becomes part of my working ‘vocabulary’, here are a few ideas I’m jotting down as I collect them:</p><p><strong>#divmod</strong></p><p>Call it on a numeric object, and it returns an array [quotient, remainder].</p><p>53.divmod(10) #=&gt; [5, 3]</p><p><strong>Assigning two variables at once</strong></p><p>word[0], word[-1] = word[-1], word[0] swaps first and last items.</p><p>quotient, remainder = 53.divmod(10)</p><p>quotient =&gt; 5 remainder =&gt; 3</p><p><strong>#ord</strong></p><p>Call it on one ascii character, and it returns the integer ordinal. Call .chr on an integer to do the opposite.</p><p><strong>&lt;=&gt;</strong></p><p>Comparison method used like an operator.</p><ul><li>Returns 1 if the first object is greater. &#39;y&#39; &lt;=&gt; &#39;x&#39; #=&gt; 1</li><li>-1 if second object is greater. &#39;x&#39; &lt;=&gt; &#39;y&#39; #=&gt; -1</li><li>0 if the two objects are equal. &#39;x&#39; &lt;=&gt; &#39;x&#39; #=&gt; 0</li></ul><p><strong>Sorting</strong></p><ul><li><strong>Array#sort, Enumerable#sort</strong>: sorts collections of like elements which can be compared with &lt;=&gt;, returning an array. Low to high without a block or, as specified using &lt;=&gt; within the block.</li></ul><pre>[‘10’, ‘11’, ‘9’, ‘7’, ‘8’].sort { |x,y| y.to_i &lt;=&gt; x.to_i }</pre><pre>#=&gt; [&quot;11&quot;, &quot;10&quot;, &quot;9&quot;, &quot;8&quot;, &quot;7&quot;]   # sorted by reverse integer value.</pre><ul><li><strong>Enumerable #sort_by, #max_by: </strong>A block specifies how to sort objects in the collection. For example, .sort_by {|word| word.length }</li></ul><p><strong>Enumerable#inject</strong> aka <strong>#reduce</strong></p><p>An iterator method with an accumulator variable. A convenient way to use this method is with a symbol for an operation.</p><p>[1, 2, 3, 4].inject(:+) returns the sum of everything in the array, or 10</p><p><strong>Enumerable#each_with_object(obj) {|(args), obj| block }</strong></p><p>Allows a second object to be manipulated during iteration, then returns the object. For example, the object could be an empty hash to be populated.</p><pre>[&#39;ant&#39;, &#39;bear&#39;, &#39;cat&#39;].each_with_object({}) do |word, new_hash|<br>  new_hash[word] = word.size<br>end<br>=&gt; {&quot;ant&quot;=&gt;3, &quot;bear&quot;=&gt;4, &quot;cat&quot;=&gt;3}</pre><p><strong>Integer#upto or downto(limit) {|i| block }</strong></p><p>Iterates beginning with the caller, including the limit as last iteration. Similar to #times</p><p><strong>Hash.new(0)</strong></p><p>initializes a new hash with a default value, such as 0, for any keys not yet in the hash. Otherwise the value is nil. Can also be done by using the defaultmethod, hash.default = 0</p><p><strong>#Array.new(3, 0)</strong></p><p>initializing a new array in this way, two arguments can be given. The first is an array size, and the second populates each element. So this example would return[0, 0, 0]</p><p><strong>Array#insert(index, obj) </strong>and<strong> String#insert(index, string)</strong></p><p>Inserts the object at the given index.</p><p><strong>#reverse_each</strong></p><p>For arrays and ranges (not strings): Same as #each but starts at the end.</p><p><strong>Enumerable#find </strong>aka <strong>#detect {block}</strong></p><p>Returns the first item for which the return value of the block evaluates to true. <strong>#find_all</strong> returns an array of all items that match.</p><p><strong>Enumerable#all? </strong>and <strong>#any?</strong></p><p>Returns true or false depending on the return value of a block.</p><p><strong>Array#find_index(obj) or find_index { |item| block }</strong></p><p>Finds index of a specific object or an object for which return value of block is truthy. Returns index or nil.</p><p><strong>array | array</strong></p><p>Combines two arrays, yielding their union (no duplicates).</p><p><strong>(&amp;:method)</strong></p><p>Think of it as shorthand for a block,{ |item| item.method }. Use with any method that takes a block. Examples:</p><ul><li>array.map(&amp;:capitalize) capitalizes the first character of every item in the array.</li><li>[1, 2, 3, 4, 5].select(&amp;:odd?) # =&gt; [1, 3, 5]</li><li>(1..9).any?(&amp;:even?) # =&gt; true</li></ul><p><strong>regex</strong></p><p>Just a couple quick notes about matching patterns in Ruby:</p><ul><li>&#39;a&#39; =~ /[a-z]/ returns an integer, the index of the first match. (0 for this example).</li><li>sets can be nested. [a-z&amp;&amp;[^aeiuo]]/i means any character a-z, case insensitive, <em>except</em> a vowel.</li><li>\b signals the beginning and end of a word. It can have a period after, but not other letters. So /\beight\b/ would match &#39;eight.&#39; but not &#39;freight&#39;</li></ul><p><strong>heredocs</strong></p><p>for printing multiple lines. Use any name.</p><pre>puts &lt;&lt;NAME<br>Line 1<br>Line 2<br>NAME</pre><p>Interpolation is allowed by default, and can be turned off by putting quotes around the heredoc name. Useful when you want a literal slash characters, rather than escape characters.</p><pre>puts &lt;&lt;&#39;NAME&#39;<br>Line 1<br>Line 2<br>NAME</pre><p><strong>printing multiple lines of code on one line</strong></p><p>The following outputs one line using \ (This could be done with + or &lt;&lt; but \ is preferred.)</p><pre>puts &quot;Some stuff &quot; \<br>     &quot;and some other stuff &quot; \<br>     &quot;and even more stuff.&quot;<br>#=&gt; Some stuff and some other stuff and even more stuff.</pre><p><strong>Converting a series of numbers to an array with a block:</strong></p><ul><li>.map<strong> </strong>1.upto(4).map { |i| i*i } <strong>#=&gt; [1, 4, 9, 16]</strong></li><li>.find all or .select (1..10).find_all { |i| i % 3 == 0 } <strong>#=&gt; [3, 6, 9]</strong></li></ul><p><strong>Array#count or Enumerable#count</strong></p><ul><li>No argument: same as .size or .length</li><li>1 argument: counts the number of elements which equal the argument</li><li>block: counts the number of elements for which the block returns a truthy value.</li></ul><p><strong>String#count</strong></p><ul><li>1 argument: defines a set of characters to count. Counts the number of occurrences of any of these characters.</li></ul><p><strong>Hash#shift</strong></p><p>Destructively removes one key — value pair (the first) and returns it as an array.</p><p><strong>Time object</strong></p><p><strong>Splat operator</strong></p><p><strong>#fetch</strong></p><p>For arrays and hashes. Why not just use [] to retrieve a value? If the value doesn’t exist, [] will return ‘nil’ but .fetch will throw an error. So .fetch can be used to find out if the value exists. Use with an optional second parameter to supply a default value, or with a block that will be executed when there is no value.</p><p><strong>String#delete(chars)</strong></p><p>A string method that deletes specified characters from anywhere in the string. word.delete(&#39;^A-Za-z&#39;) deletes any non-alphabetic characters.</p><p><strong>Selecting a sub-array</strong></p><p>There are many methods for this, but array[] or .select will usually do the job!</p><ul><li>array[range of index numbers], or array[starting_index, length] (which calls .slice).</li><li>.select or .select! {block} returns a new array containing values for which the block evaluates to true.</li><li>.values_at(indexes or ranges)</li><li>.first(length) starts at 0. If no argument, returns just the first element.</li><li>.last(length) starts at the end. If no argument, returns the last element.</li><li>.take(length) starts at 0.</li><li>.take_while {block} starts at 0, continues until block is false.</li><li>.drop(n) drops the first n elements, returns the rest.</li><li>.shift(n) deletes the first n elements, returns the rest.</li><li>.pop(n) deletes the last n elements and returns them.</li><li>drop_while {block} drops elements until block is false, returns the rest.</li><li>.slice or .slice!, with (index), (start_index, length), or (range)</li><li>.delete_if {block} Returns what is not deleted, mutating the caller. (Note: don’t use .delete to get a sub-array. It returns only the last element deleted. Unlike string#delete, which returns the entire deleted portion.)</li><li>.reject or .reject! {block} returns elements for which the block is false.</li><li>.keep_if {block}</li></ul><p><strong>Selecting a sub-hash</strong></p><p>Just for comparison purposes.</p><ul><li>.select or .select! {|k,v| block}</li><li>.delete_if {block} returns what is not deleted</li><li>.reject or .reject! {|k,v| block}</li><li>.keep_if {|k,v| block}</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee4907b9fd51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Kernel.format]]></title>
            <link>https://medium.com/@kristenfletcherwilde/getting-started-with-kernel-format-7c7645266fed?source=rss-f582634ec512------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c7645266fed</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kristen Fletcher Wilde]]></dc:creator>
            <pubDate>Fri, 28 Oct 2016 19:56:34 GMT</pubDate>
            <atom:updated>2016-11-07T15:58:39.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Kernel#format in Ruby is a convenient way to format output values as strings. Before we get into the details, here are a few possible uses:</p><ul><li>round floats to a specified number of decimal places ($4.39)</li><li>display a specified number of digits, padding with zeroes (12:05 pm)</li><li>format large/small numbers as exponential notation</li><li>truncate strings to a specified number of characters and justify left or right</li></ul><p>The basic syntax:</p><p><strong>format(format_string, arguments_to_be_formatted)</strong></p><p>The format string is a sequence of elements wrapped in quotes, beginning with a percent sign. The elements in [brackets] are optional:</p><p><strong>“%[flags][width][.precision]type”</strong></p><h4><strong>Type</strong></h4><p>The last element in the format string, the <strong>field type</strong> is indicated with one character, probably</p><p>d or i for integer (decimal number),</p><p>f for float, or</p><p>s for string.</p><p>Or maybe e or g for exponential notation. (For other options — the .inspect value, a character code, hexadecimal, octal, binary, and capital letter versions of the above — see the <a href="https://ruby-doc.org/core-2.3.0/Kernel.html#method-i-format">docs</a>.)</p><h4>Precision</h4><p><strong>Precision </strong>is written with a period and an integer. It controls the number of characters displayed, behaving differently depending on the field type. Here’s what .2 precision looks like for different types:</p><p>format(&quot;%.2f&quot;, 3.14159) =&gt; 3.14 for a float, places after the decimal point</p><p>format(&quot;%.2d&quot;, 3.14159) =&gt; 03 for an integer, total decimal places</p><p>format(“%.2s”, “pie”) =&gt; “pi” for a string, <em>maximum</em> characters</p><p>format(“%.2s”, “p”) =&gt; “p” for a string, no fill characters (unlike integer)</p><p>format(“%.2e”, 31_415_900) =&gt; “3.14e+07” for exponent type e, places after the decimal point</p><p>format(“%.2g”, 31_415_900) =&gt; “3.1e+07” for exponent type g, total significant digits</p><h4><strong>Width</strong></h4><p>The <strong>width</strong> is an integer that specifies the <em>minimum</em> number of characters to output. Fill is done with spaces by default.</p><p>format(“%2s”, “p”) =&gt; “ p”</p><p>format(“%2d”, 3.14) =&gt; “ 3”</p><p>format(“%2f”, 3.14) =&gt; “3.140000” Unexpected! Please comment if you can explain this to me.</p><p>format(“%8.5f”, 3.14) =&gt; “ 3.14000” When precision is specified, width works as expected on a float ( The decimal point . counts as a character).</p><h4>Flags</h4><p>Flags are characters which modify the behavior of the format. 0, whitespace, +, -, *, and # are flag characters.</p><p>+ <strong>adds a sign</strong>, ‘+’ positive or ‘-’ negative, to numeric types</p><p>format(“%+d”, 3) =&gt; “+3”</p><p>format(“%+d”, -3) =&gt; “-3”</p><p>[whitespace] <strong>adds a ‘-’</strong> when negative and leaves a space when positive.</p><p>format(“% d”, -3) =&gt; “-3” <br> format(“% d”, 3) =&gt; “ 3”</p><p>Note: if no flags are given with a negative argument, the output will still have a ‘-’.</p><p>format(“%d”, -3) =&gt; “-3”</p><p><strong>- left-justifies</strong> the result within the given width.</p><p>format(“%-8.5f”, 3.14) =&gt; “3.14000 “</p><p>0 <strong>pads with 0’s</strong> for numeric types.</p><p>format(“%05d”, 3.14) =&gt; “00003”</p><p>format(“%011.5f”, 3.14) =&gt; “00003.14000”</p><p>format(“%-+07.5d”, 3.14) =&gt; “+00003 “</p><p>(To specify padding for strings, use <a href="https://ruby-doc.org/core-2.3.0/String.html#method-i-rjust">#rjust</a>, <a href="https://ruby-doc.org/core-2.3.0/String.html#method-i-ljust">#ljust</a>, and <a href="https://ruby-doc.org/core-2.3.0/String.html#method-i-center">#center</a> rather than #format.)</p><p># <strong>formats non-integers</strong> in different ways. It tells floats and exponentials to show the decimal point, and adds prefixes to non-base10 numbers.</p><p>format(“%#05.0f”, 3.14) =&gt; “0003.”</p><p>format(“%#.1G”, 31_415_900) =&gt; “3.E+07”</p><p>format(“%#b”, 3) =&gt; “0b11” binary with flag # adds prefix ‘0b’</p><p>*<strong> and </strong>$<strong> indicate alternate syntax</strong> for the format width . . . but this is enough information on Kernel.format for now, at least for me! Feel free to take a stab at explaining this syntax in the comments, or link to an explanation for me. I’d like to know when and why it would be useful. (For dealing with multiple arguments, maybe??)</p><h4>Other characters</h4><p>The format string can also include other characters, before or after the elements described above. These extra characters will be added to the result. For example, $ for a money value.</p><p>format(“$%.2f”, 1.94741) =&gt; &quot;$1.95&quot;</p><h4>More</h4><p><a href="https://ruby-doc.org/core-2.3.0/Kernel.html#method-i-format">Ruby.doc.org</a> says “For more complex formatting, Ruby supports a reference by name %&lt;name&gt;”. Another topic for another time! (Again, feel free to comment about this.)</p><p>Thanks for reading this introduction to Kernel.format! I think I now have a pretty good understanding of the basics of using this method, and I hope it’s helped you too!</p><h3>Practice</h3><p>Try to come up with a format string for each of these examples, then scroll down for the answers. I’ve used variables rather than values, as I would when writing a program.</p><ol><li>Shorten a name to just three characters and preface it with a space.</li></ol><p>format(“_______”, name) =&gt; “ Lis”</p><p>2. Round an amount of money to dollars and cents. The resulting string should be the same length whether the total is positive or negative.</p><p>format(&quot;________&quot;, total) =&gt; &quot;$ 37.94&quot;</p><p>3. Display a a large number such as 123_456 in exponential notation with two digits following the decimal point and two leading zeroes.</p><p>format(&quot;______&quot;, num) =&gt; “001.23e+05”</p><p>4. Display clock time.</p><p>format(“________”, hours, minutes) =&gt; &quot;03:05&quot;</p><p>hint: “%___:%___”</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>Answers:</p><ol><li>“%4.3s”</li><li>“$% .2f”</li><li>“%010.2e”</li><li>“%02d:%02d”</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c7645266fed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>