<?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 Annee Barrett on Medium]]></title>
        <description><![CDATA[Stories by Annee Barrett on Medium]]></description>
        <link>https://medium.com/@anneeb?source=rss-cb312fa5962c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lWueUA6sEzwdhXfQ.</url>
            <title>Stories by Annee Barrett on Medium</title>
            <link>https://medium.com/@anneeb?source=rss-cb312fa5962c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:13:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anneeb/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[Redirecting in React]]></title>
            <link>https://medium.com/@anneeb/redirecting-in-react-4de5e517354a?source=rss-cb312fa5962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4de5e517354a</guid>
            <category><![CDATA[javasc]]></category>
            <category><![CDATA[react-rout]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Annee Barrett]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 02:58:51 GMT</pubDate>
            <atom:updated>2018-07-27T18:26:53.528Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sometimes you just want to get away…</h4><p>Single page websites are great because they dynamically update as the user interacts with application, thus allowing for shorter loading times between pages. Although the page never actually reloads or sends you to a new route, the app mimics this behavior by manipulating the window’s history or location objects. Using a link to navigate to a new page with is pretty straightforward: a user interacts with an element, and that event triggers the history or location change. Redirecting proves to be more difficult, as the routing action needs to be fired based on the state of the application.</p><h4>Redirect Component</h4><p>If you have routes in your React app, you’re probably using React Router (or React Router DOM) to set up your routes. Considering you’ve already installed the React Router library, the easiest way to redirect to a new location is by using its Redirect component. When the component is rendered, the existing location of the history object is replaced with a new location. If you don’t want to override the existing history location, including the push property will push a new entry onto the history.</p><pre>import React from &#39;react&#39;<br>import { Redirect } from &#39;react-router-dom&#39;</pre><pre>class MyComponent extends React.Component {</pre><pre>  state = {<br>    redirect: false<br>  }</pre><pre>  setRedirect = () =&gt; {<br>    this.setState({<br>      redirect: true<br>    })<br>  }</pre><pre>  renderRedirect = () =&gt; {<br>    if (this.state.redirect) {<br>      return &lt;Redirect to=&#39;/target&#39; /&gt;<br>    }<br>  }</pre><pre>  render () {<br>    return (<br>       &lt;div&gt;<br>        {this.renderRedirect()}<br>        &lt;button onClick={this.setRedirect}&gt;Redirect&lt;/button&gt;<br>       &lt;/div&gt;<br>    )<br>  }</pre><pre>}<br></pre><p>This route (haha) is not the best if you’re not a fan of controlled components, that is, it has and is responsible for its own state. Luckily, we can still accomplish this behavior manually by passing props!</p><h4>Route Component Props</h4><p>The Route component provides three props to whatever component it renders: location, match and history. Passing down these props to a nested component gives us access to the history object, which we can then push a new location onto.</p><pre>import React from &#39;react&#39;<br>import { BrowserRouter, Route } from &#39;react-router-dom&#39;</pre><pre>class MyRouter extends React.Component {</pre><pre>  render () {<br>    return (<br>      &lt;BrowserRouter&gt;<br>        &lt;Route <br>          path=&#39;/&#39;<br>          render={ props =&gt; &lt;MyComponent {...props} /&gt;}<br>        /&gt;<br>      &lt;/BrowserRouter&gt;<br>    )<br>  }</pre><pre>}</pre><pre>class ParentComponent extends React.Component {</pre><pre>  render () {<br>    return &lt;ChildComponent {...this.props} /&gt;<br>  }</pre><pre>}</pre><pre>class ChildComponent extends React.Component {</pre><pre>  redirectToTarget = () =&gt; {<br>    this.props.history.push(`/target`)<br>  }</pre><pre>  render () {<br>    return (<br>       &lt;div&gt;<br>        {this.renderRedirect()}<br>        &lt;button onClick={this.redirectToTarget}&gt;Redirect&lt;/button&gt;<br>       &lt;/div&gt;   <br>    )<br>  }</pre><pre>}</pre><p>But what if the component that needs the redirect functionality is nested super deep? Passing these props through all the components between the route and your child component is not ideal, so here is a third (but not recommended) option: Context and PropTypes</p><h4>Context and PropTypes</h4><p>In order to add the context parameter to a React component, we need to define context types as a PropTypes.object. This passes the props directly from the Router component to our child component. Now that we have access to the router props, we also have access to the history, and can push a new entry onto it with a new target location.</p><pre>import React from &#39;react&#39;<br>import { BrowserRouter, Route } from &#39;react-router-dom&#39;<br>import PropTypes from &#39;prop-types&#39;</pre><pre>class MyRouter extends React.Component {</pre><pre>  render () {<br>    return (<br>      &lt;BrowserRouter&gt;<br>        &lt;Route path=&#39;/&#39; component={MyComponent} /&gt;<br>      &lt;/BrowserRouter&gt;<br>    )<br>  }</pre><pre>}</pre><pre>class ParentComponent extends React.Component {</pre><pre>  render () {<br>    return &lt;ChildComponent /&gt;<br>  }</pre><pre>}</pre><pre>class ChildComponent extends React.Component {</pre><pre>  static contextTypes = {<br>    router: PropTypes.object<br>  }</pre><pre>  redirectToTarget = () =&gt; {<br>    this.context.router.history.push(`/target`)<br>  }</pre><pre>  render () {<br>    return (<br>       &lt;div&gt;<br>        {this.renderRedirect()}<br>        &lt;button onClick={this.redirectToTarget}&gt;Redirect&lt;/button&gt;<br>       &lt;/div&gt;   <br>    )<br>  }</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4de5e517354a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJs Observables]]></title>
            <link>https://medium.com/@anneeb/rxjs-observables-577129d0d227?source=rss-cb312fa5962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/577129d0d227</guid>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Annee Barrett]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 20:25:33 GMT</pubDate>
            <atom:updated>2017-07-05T20:25:33.855Z</atom:updated>
            <content:encoded><![CDATA[<p>Reactive Javascript’s observables are similar to promises in that they both are an object that represents the eventual completion (or failure) of an asynchronous function. But in their execution, ability to handle multiple events, and features, observables have much more interesting functionality.</p><h4>Set Up</h4><pre>// CDN &lt;script src=&quot;<a href="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.3/dist/global/Rx.umd.js">https://npmcdn.com/@reactivex/rxjs@version/dist/global/Rx.umd.js</a>&quot;&gt;&lt;/script&gt;</pre><pre>// in console<br>npm install rxjs-es</pre><pre>// in javascript<br>import { Observable} from &#39;rxjs/Observable&#39;</pre><h4>Creation, Execution and Multiple Events</h4><pre>const simpleObs = Rx.Observable.create(callback)</pre><pre>const fromEvent = Rx.Observable.fromEvent(target, eventName)</pre><pre>const fromProm = Rx.Observable.fromPromise(promise)</pre><p>In its simplest form, an observable is created by using the create method. Otherwise, there are a number of creation operators available <a href="http://reactivex.io/rxjs/manual/overview.html#creation-operators">here</a>.</p><p>While promises use eager execution, observables use lazy execution. That is, rather than executing immediately, an observable will only execute when it is needed. Additionally, a promise can only be responsible for a single event, but an observable can handle zero or more.</p><h4>Debouncing</h4><pre>Rx.Observable.fromEvent(target, &#39;keyup&#39;)<br>  .debounceTime(500)<br>  .subscribe(event =&gt; console.log(event.target)</pre><p>In this case, the observable will keep track of every emission, but will only emit the most recent item after the set time span has passed without another emission.</p><h4>Throttling</h4><pre>Rx.Observable.fromEvent(target, &#39;mousemove&#39;)<br>  .throttleTime(500)<br>  .subscribe(event =&gt; console.log(event.x, event.y)</pre><p>Like debouncing, throttling limits how often it can emit a value. It will keep collecting emissions, but will only emit once per the set time span.</p><h4>Cancellation</h4><pre>let obs = Rx.Observable.create(callback)</pre><pre>// somewhere else <br>obs.unsubscribe()</pre><p>You can cancel an observable by unsubscribing from it.</p><h4>Error Handling</h4><pre>Rx.Observable.fromPromise($.get(&#39;<a href="https://bad.api&/#39;">https://bad.api&#39;</a>)<br>  .catch(err =&gt; {<br>    return Rx.Observable.fromPromise(fetch(&#39;<a href="https://api.github.com/users/UmaMoiseenko&#39;">https://good.api&#39;</a>))<br>  })<br>  .subscribe(res =&gt; console.log(res), err =&gt; console.log(&#39;error!&#39;))</pre><p>Error handling allows for you to set up a fallback option.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577129d0d227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Generators]]></title>
            <link>https://medium.com/@anneeb/javascript-generators-42ec37c25b80?source=rss-cb312fa5962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/42ec37c25b80</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[generator]]></category>
            <dc:creator><![CDATA[Annee Barrett]]></dc:creator>
            <pubDate>Wed, 14 Jun 2017 16:30:57 GMT</pubDate>
            <atom:updated>2017-06-14T17:33:49.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Iterators allow us to repeat a procedure over a collection without having to define the procedure for every object in the collection. Here’s how you’d print the values of an array using a while loop to iterate:</p><pre>function printArray(arr) {<br>  let i = 0<br>  while (i &lt; arr.length) {<br>    console.log(arr[i++])<br>  }<br>}</pre><pre>printArray([1, &quot;mrow&quot;, false])   // 1<br>                                 // mrow<br>                                 // false</pre><p>But what if you have a super long array, and don’t want to wait until the entire collection has been iterated over before running something else? Unfortunately, we can’t pause iterators, but we do have generators!</p><p>Generators are able to define an iterative algorithm in a single function that is able to maintain its state. Unlike the <em>synchronous</em> function above, these functions are <em>asynchronous</em>, that is, the function doesn’t need to wait for the its entire completion before it can start returning values.</p><p>Here is the previous example written using a generator:</p><pre>function* returnArray(arr) {<br>  let i = 0<br>  while (i &lt; arr.length) {  <br>    yield arr[i++]<br>  }<br>}</pre><pre>var items = returnArray([1, &quot;meow&quot;, false])</pre><pre>console.log(items.next().value)   // 1<br>console.log(items.next().value)   // meow&quot;<br>console.log(items.next().value)   // false<br>console.log(items.next().value)   // undefined</pre><h3>Defining a Generator</h3><p>Like regular functions, generators can be created using generator declaration, expression, and constructors:</p><h4>Generator Declaration</h4><pre>function* name() {} </pre><p>As with regular function declaration, the generator’s name is visible within it’s scope and the scope of it’s parent.</p><h4>Generator Expression</h4><pre>var anon = function* () {}<br>var notAnon = function* name() {}</pre><p>As with regular function expression, these generators are not hoisted and cannot be called before the generator is defined.</p><h4>Generator Constructor</h4><pre>var gen = new GeneratorFunction ([arg, ..., arg], functionBody) </pre><h3>The Generator Object and its Methods</h3><pre>function* sayHello() {<br>   yield &quot;hello&quot;<br>}</pre><pre>var helloGen = sayHello()</pre><pre>console.log(sayHello)     // [Function: sayHello]<br>console.log(sayHello())   // {}<br>console.log(helloGen)     // {}</pre><p>When invoked, a generator function returns a generator object. In order to actually execute the code within the generator, we need to use generator methods on this object.</p><h4>Next</h4><pre>function* countToThree() {<br>  let i = 1<br>  while (i &lt;= 3) {  <br>    yield i++<br>  } <br>  console.log(&quot;I&#39;m done counting!&quot;)<br>}</pre><pre>var gen = countToThree()</pre><pre>console.log(gen.next())   // {value: 1, done: false}<br>console.log(gen.next())   // {value: 2, done: false}<br>console.log(gen.next())   // {value: 3, done: false}<br>console.log(gen.next())   // I&#39;m done counting!<br>                          // {value: undefined, done: true}</pre><p>When the next method is called, the generator executes the code block until the first yield expression. The method will return an object that has two properties, value, the expression following the yield keyword, and done, a boolean that indicates whether the generator is finished.</p><h4>Return</h4><pre>function* infiniteCount() {<br>  let i = 1<br>  while (true) {  <br>    yield i++<br>  } <br>}</pre><pre>var gen = infiniteCount()</pre><pre>console.log(gen.next())          // {value: 1, done: false} console.log(gen.return(&quot;fin&quot;))   // {value: &quot;fin&quot;, done: true}</pre><p>When the return method is called, the generator will return whatever argument it is passed as its value, and end the generator.</p><h4>Throw</h4><pre>function* genWithError() {<br>  while(true) {<br>    try {<br>       yield &quot;no errors here&quot;;<br>    } catch(e) {<br>      console.log(&#39;error!&#39;);<br>    }<br>  }<br>}</pre><pre>var gen = genWithError()<br>var err = new Error(&#39;whoops&#39;)</pre><pre>console.log(gen.next())       // { value: 42, done: false }<br>console.log(gen.throw(err))   // { value: &#39;error!&#39;, done: false }</pre><p>When the throw method is called, it throws an error into the generator. causing it to execute its catch block.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42ec37c25b80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Options of Rails Commands]]></title>
            <link>https://medium.com/@anneeb/the-options-of-rails-commands-4b29effa9a8f?source=rss-cb312fa5962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b29effa9a8f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Annee Barrett]]></dc:creator>
            <pubDate>Tue, 23 May 2017 04:17:30 GMT</pubDate>
            <atom:updated>2017-05-23T04:31:15.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>Things you can choose to not include when creating with rails</h4><p>Rails is pretty good at creating files and folder structures. In fact, it’s so good at it, I find it kind of overwhelming. With just three words (<strong><em>rails new app</em></strong>), a new “app” directory appears, and in it, over 100 (well, exactly 101) files and folders. Run a few <strong><em>rails generate</em></strong> commands on top of that and your app’s fully expanded project tree is now taller than you. Eek.</p><p>Depending on what you’re working on, you might not want or need all of what these rails commands create. If your heart desires, you could go through after all these files and folders have been created and delete what you don’t want, but luckily, there’s a simpler way: we have options!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9sbRdVPPN3zD331qpQUHQ.jpeg" /><figcaption>a cat on rails</figcaption></figure><h3>Rails New</h3><pre>rails new APP_PATH [options]</pre><p>When you run the <strong><em>rails new</em></strong> command in your terminal, you have a list of options to choose from. Like its name would suggest, these commands are completely optional, and the code will run fine without including them. Simply append as many as you’d like to the end of the command, and rails magic will do the rest! There are many options to choose from, but as to keep with the theme of this post, here are some of the most common files and folders you can choose to skip in the creation of a rails app, they even have their own shorthands:</p><pre>Action Cable files: -C or --skip-action-cable</pre><pre>.gitignore file: -G or --skip-git</pre><pre>JavaScript files: -J or --skip-javascript</pre><pre>Action Mailer files: -M or --skip-action-mailer</pre><pre>Active Record files: -O or --skip-active-record</pre><pre>Puma related files: -P or --skip-puma</pre><pre>Sprockets files: -S or --skip-sprockets</pre><pre>Test files: -T or --skip-test</pre><p>For the full list of options, run <strong><em>rails new -h</em></strong> in your terminal.</p><h3>Rails Generate</h3><pre>rails generate GENERATOR [arguments] [options]</pre><p>Like creating a new rails app, rails generators are executed in the terminal by following the above structure. A list of all the generators available can be printed by running <strong><em>rails g -h</em></strong>, where <strong><em>g</em></strong> is an alias and can be used interchangeably for <strong><em>generate</em></strong>. Here are some of the options that default to their true counterparts that you may choose to not include:</p><h4>Tests</h4><pre>Tests: --no-test-framework</pre><ul><li>Available when generating: controller, generator, helper, job, mailer, model, model, resource, scaffold_controller, scaffold</li></ul><h4>Asset Options</h4><pre>Javascripts: --no-javascripts<br>Stylesheets: --no-stylesheets</pre><ul><li>Available when generating: asset, controller, resource, scaffold</li><li>Additionally, you can choose not to create any assets when generating a channel, controller, resource, or scaffold with the following:</li></ul><pre>Assets: --no-assets</pre><h4>Controller Options</h4><pre>Routes: --skip-routes<br>Helper: --no-helper</pre><ul><li>Available when generating: controller, resource</li></ul><h4>Active Record Options</h4><pre>Migrations: --no-migration<br>Timestamps: --no-timestamps<br>Indexes: --no-indexes</pre><ul><li>Available when generating: model, resource, scaffold</li></ul><h4>Scaffold Controller Options</h4><pre>API controller: --no-api<br>Helper: --no-helper<br>Jbuilder: --no-jbuilder</pre><ul><li>Available when generating: scaffold, scaffold_controller</li></ul><h4>Scaffold Options</h4><pre>Resource route:  --no-resource-route<br>Scaffold stylesheet: --no-scaffold-stylesheet</pre><ul><li>Only available when generating a scaffold</li></ul><p>If you’d like to see a full list of all options for a given generator, inside of a rails app folder in your terminal, run <strong><em>rails g &lt;generator&gt; -h</em></strong>.</p><h4>So instead of deleting a handful of files, you can tag an option on the end of your rails command and get back to writing code! *phew*</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b29effa9a8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recreating the Flatten Method in Ruby]]></title>
            <link>https://medium.com/@anneeb/recreating-the-flatten-method-for-arrays-in-ruby-fae8040bdbde?source=rss-cb312fa5962c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fae8040bdbde</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Annee Barrett]]></dc:creator>
            <pubDate>Thu, 04 May 2017 05:18:37 GMT</pubDate>
            <atom:updated>2017-05-04T17:29:17.178Z</atom:updated>
            <content:encoded><![CDATA[<h4>An exercise in classes, methods, and recursion</h4><p>As someone who first started learning how to code in Javascript, “for” loops have a special place in my heart. Iterating over a collection always involved or used a helper method with some long, extremely explicit “for” loop. So when I started learning Ruby, I was immediate skeptical about its immense selection of built in-methods, iterators, and enumerables. How did .each know where to start and stop iterating if I wan’t giving it a counter? Where did .map or .collect hold its working information?</p><p>My understanding of how Ruby iterators worked was answered through exercises where I recreated the .each and .map methods using yield, which I’m not going to go into. Instead, I’m going to walk you thorough my solution for a prompt that I encountered when applying to a coding bootcamp: recreating Ruby’s flatten method for arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Gdq4Gvgmzt2DqTrvIYVYg.jpeg" /><figcaption>a flat cat</figcaption></figure><h3>Ruby’s Flatten</h3><p>Say you have an array of <em>nested, or multidimensional, arrays</em>, that is, an array in which there are elements that are also arrays:</p><pre>array = [1, [2, 3, [4, 5]]]</pre><p>The flatten method will return a one-dimensional array, an array where all the values are on the same level:</p><pre>array = [1, [2, 3, [4, 5]]]<br>array.flatten #=&gt; [1, 2, 3, 4, 5]</pre><p>Additionally, you can call the flatten method with an argument, which will flatten that array by that many levels:</p><pre>array = [1, [2, 3, [4, 5]]]<br>array.flatten(1) #=&gt; [1, 2, 3, [4, 5]]</pre><h3>Object Oriented Ruby</h3><p>Ruby is an object-oriented language. Almost everything in Ruby is an object, and every object has a class and is an instance of that class. Ruby includes a default collection of methods for objects that vary for different classes, which is how we’re able to use .flatten on receivers that are arrays or hashes, (although .flatten works slightly differently on hashes,) and not on those that are numbers or strings. But how do we know what the class of an object is? Of course, there’s a method for that: .class!</p><pre>arr = [1, [2, 3, [4, 5]]]<br>arr.class #=&gt; Array</pre><pre>[1, [2, 3, [4, 5]]].class #=&gt; Array</pre><p>We’ll be using this method in our custom flatten method to determine whether elements of the array are also arrays.</p><h3>Class Methods</h3><p>Let’s start by defining the method my flatten for the Array class:</p><pre>class Array</pre><pre>  def my_flatten<br>    # code goes here<br>  end</pre><pre>end </pre><p>This way, the my_flatten method is accessible to any object that is an instance of the Array class.</p><h3>Default Arguments</h3><p>We want our method to flatten an array by a given number of dimensions if an argument is passed, but completely flatten an array if no argument is passed. Therefore, our method must be able to take in an optional argument. By setting the parameter to <em>n = nil</em>, we are telling Ruby that if this argument is not defined when the method is called, the method will pass a default value, which for our purposes will be <em>nil</em>.</p><p>Our method should do one thing if <em>n</em> has a value, and another if <em>n</em> does not. I’ve chosen to use a ternary operator that checks the truthiness of <em>n</em>, as if <em>n </em>has a value it will return <em>true</em>, and if <em>n </em>is equal to <em>nil</em> it will return <em>false</em>:</p><pre>def my_flatten(n = nil)<br>  n ? method_if_n(self, n) : method_if_no_n(self)<br>end</pre><p>Because we want our method to operate on the receiver, we use <em>self </em>to refer to the instance on which the method is being called.</p><p>Now let’s write our flattening methods!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*ruYvbwy3H_sOvh-cZeEwfw.jpeg" /><figcaption>a collection of flattened cats</figcaption></figure><h3>Flattening an Array by One Dimension</h3><p>We’re going to start by defining a helper method that flattens an array by one dimension:</p><pre>def single_flatten(array)<br>  results = []<br>  array.each do |element|<br>    if element.class == Array<br>      element.each {|value| results &lt;&lt; value}<br>    else<br>      results &lt;&lt; element<br>    end<br>  end<br>  results<br>end</pre><p>This method takes in an array and sets an empty results array. It then looks at each element of the array in question. If the element is an array, it will look at each element within that array, and append the nested element’s value to the results array using the shovel operator. If the element is not an array, it will append the value of that element into the the results array. Once every element in the array has either had itself or its components appended into the results, the method returns the result array, which is equivalent to the original array flattened by one dimension:</p><pre>my_array = [1, [2, 3, [4, 5]]]<br>single_flatten(my_array) #=&gt; [1, 2, 3, [4, 5]]</pre><h3>Flattening an Array <em>n</em> Times</h3><p>But what if we want to flatten an array a given number of times? We can call single_flatten within a while loop with a counter:</p><pre>def multiple_flatten(array, n)<br>  count = 0<br>  arr = array<br>  while count &lt; n do<br>    arr = single_flatten(arr)<br>    count += 1<br>  end<br>  arr<br>end</pre><p>First, we set the count to zero and the variable <em>arr</em> to our initial array. If the counter hasn’t reached the number of dimensions we’ve specified wanting to reduce our array by, <em>arr</em> will be passed into single_flatten. Every time the block in the while loop executes, <em>arr</em> is reassigned to the result of single_flatten, and the counter is incremented by one. Once the counter is equal to the number of dimensions we want to reduce by, the final return value of the method is <em>arr</em>, the last result of the single_flatten.</p><pre>my_array = [1, [2, 3, [4, [5, 6]]]]<br>multiple_flatten(my_array, 2) #=&gt; [1, 2, 3, 4, [5, 6]]</pre><h3>Flattening an Array with Recursion</h3><p>Our last helper method is the recursive flatten:</p><pre>def recursive_flatten(array, results = [])<br>  array.each do |element|<br>    if element.class == Array<br>      recursive_flatten(element, results)<br>    else<br>      results &lt;&lt; element<br>    end<br>  end<br>  results<br>end</pre><p>Like the single flatten, it checks if an element is an array, and if not, appends the value of the element to a results array. However, if the element is an array, the method calls itself pulling in this element and the existing results array. The method will keep calling itself on the elements of elements until all the elements are not arrays and can be pushed into the results array.</p><p>Because we want the method to be completely recursive, we’re setting results to an optional argument that defaults to an empty array. If we set the results array to be empty within the method, it will reset the results array every time the function is called. The first time we call recursive_flatten, we call it without the results argument. This way, it will create our initially empty results array that will then be filled passed around and into the other recursive_flatten methods and never be reset back to being empty!</p><p>We can now reduce a multi-dimensional array to one dimension, regardless of how many dimensions it starts with:</p><pre>my_array = [1, [2, 3, [4, 5]]]<br>recursive_flatten(my_array) #=&gt; [1, 2, 3, 4, 5]</pre><h3>Putting It All Together</h3><p>Calling the multiple_flatten and recursive_flatten methods into your ternary operator and inserting the helper methods into the class definition, we get:</p><pre>class Array</pre><pre>  def my_flatten(n = nil)<br>    n ? multiple_flatten(self, n) : recursive_flatten(self)<br>  end</pre><pre>  private</pre><pre>  def recursive_flatten(array, results = [])<br>    array.each do |element|<br>      if element.class == Array<br>        recursive_flatten(element, results)<br>      else<br>        results &lt;&lt; element<br>      end<br>    end<br>    results<br>  end</pre><pre>  def multiple_flatten(array, n)<br>    count = 0<br>    arr = array<br>    while count &lt; n do<br>      arr = single_flatten(arr)<br>      count += 1<br>    end<br>    arr<br>  end</pre><pre>  def single_flatten(array)<br>    results = []<br>    array.each do |element|<br>      if element.class == Array<br>        element.each {|value| results &lt;&lt; value}<br>      else<br>        results &lt;&lt; element<br>      end<br>    end<br>    results<br>  end</pre><pre>end</pre><p>Because the helper methods should never need to be called with an explicit receiver, I’ve chosen to make the helper methods private<em>.</em></p><p>And now, after running this code in your environment, you’ll be able to flatten objects that are array with .my_flatten!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*nEKYWd00l4IOp2G4tghNQw.gif" /><figcaption>*squish*</figcaption></figure><p>Happy flattening~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fae8040bdbde" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>