<?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 Dana C on Medium]]></title>
        <description><![CDATA[Stories by Dana C on Medium]]></description>
        <link>https://medium.com/@danacc?source=rss-7e626f3316e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YTysf-rs0qTO8d_4XDUCeg.png</url>
            <title>Stories by Dana C on Medium</title>
            <link>https://medium.com/@danacc?source=rss-7e626f3316e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:54:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danacc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to update React 17 to 18]]></title>
            <link>https://medium.com/@danacc/how-to-update-react-17-to-18-0ec844df147b?source=rss-7e626f3316e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ec844df147b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dana C]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 07:23:42 GMT</pubDate>
            <atom:updated>2024-04-25T07:23:42.622Z</atom:updated>
            <content:encoded><![CDATA[<p>How to update from React 17 to 18</p><p>If you have a large and somewhat aged codebase, it can be quite a journey to perform a React upgrade. Having gone through one of those recently, here are some things I learned when upgrading React 17 to 18.</p><p>First things first, there are some new features introduced in React 18 that might introduce breaking changes to your application or tests that are worth knowing about ahead of time. One of the things I wish I had done before making any changes was to give those changes a good read.</p><p><strong>Automatic batching</strong></p><p>Updates inside Promises, setTimeout, and event handlers are now batched. To understand this, I found the following examples that demonstrated how state changes are handled.</p><p>React 17: when multiple states change, they are batched, and <a href="https://codesandbox.io/p/sandbox/spring-water-929i6?file=%2Fsrc%2Findex.js%3A17%2C50">one update takes place</a></p><p>React 17: when multiple states change take place after another event is handled, those <a href="https://codesandbox.io/p/sandbox/trusting-khayyam-cn5ct?file=%2Fsrc%2Findex.js">state changes are not batched</a></p><p>React 18: when multiple states change take place after another event is handled, those <a href="https://codesandbox.io/p/sandbox/morning-sun-lgz88?file=%2Fsrc%2Findex.js%3A11%2C49">state changes ARE batched</a></p><p><strong>startTransition()</strong></p><p>There are a number of <a href="https://react.dev/reference/react/useTransition">good user</a> cases for this improvement, the one that seems most relevant for most applications is the following.</p><p>Previously, if a user clicks on a button that renders a process, and immediately changes their mind and clicks on another button, there is a momentary freeze while the app renders the slow process.</p><p>In the new situation, the state update is marked as a transition, and the slow process does not freeze the page.</p><p><strong>Suspense on server</strong></p><p>Using the new component Suspense, we can now defer the loading of slow components by wrapping the slow components inside it, replaced with loading state. This seems particularly pertinent to any heavy applications that struggles with lengthy loading time.</p><figure><img alt="https://www.youtube.com/watch?v=pj5N-Khihgc&amp;ab_channel=ReactConf2021" src="https://cdn-images-1.medium.com/max/438/1*04ueyS9CyYNaWyAoM2QLXQ.png" /><figcaption><a href="https://www.youtube.com/watch?v=pj5N-Khihgc&amp;ab_channel=ReactConf2021">https://www.youtube.com/watch?v=pj5N-Khihgc&amp;ab_channel=ReactConf2021</a></figcaption></figure><p><strong>Strict Mode behaviour</strong></p><p>This can be another potentially breaking change for your application. The new <a href="https://legacy.reactjs.org/docs/strict-mode.html#:~:text=To%20help%20surface%20these%20issues,state%20on%20the%20second%20mount.">Strict Mode</a> mounts, unmounts, and remounts every component in DEVELOPMENT (React 17 apparently does this too, but suppressed the logs). Note that this does not affect anything in production, and is introduced to test the resilience of your application against multiple mounts and dismount, pave the way for possible changes in that direction for production in a future release.</p><p>This means that in development, React will simulate create, destroys, and create the states again during the loading. Problems usually come with states that are created but not properly destroyed in useEffect, and might introduce bugs into your tests when combined with some of the other above mentioned <a href="https://www.dhiwise.com/post/deep-dive-into-react-concurrent-mode-exploring-key-features-and-use-cases">concurrency features</a> the React 18 introduces.</p><p><strong>New hooks</strong></p><ul><li>useId()</li><li>useTransition()</li><li>useDeferredValue()</li><li>useSyncExternalStore()</li><li>useInsertionEffect()</li></ul><p>Here’s a step by step run-down of what you should do during the upgrade.</p><ol><li>Upgrade react, react-dom, types</li><li>Replace `ReactDOM.render` with `createRoot` to unlock React 18 concurrency features</li><li>Update any library specifically related to a previous React version. For example, I had to find a replacement Enzyme adapter libary to replace an older version that only served React 17.</li><li>Update any libraries with dependencies to the older version of React.</li></ol><p>One of the issues that arose in the tests was related to what I suspect to be React’s concurrency changes. Tests that required component mounting and then checking against snapshots or the correct actions getting dispatched, might start to fail without wrapping them in either act() or waitFor().</p><p>There might also be adjustments needed to ensure that certain actions are dispatched only once when useEffect runs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ec844df147b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object.create() vs. Object.assign()]]></title>
            <link>https://medium.com/@danacc/object-create-vs-object-assign-a14bfef43df9?source=rss-7e626f3316e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14bfef43df9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <dc:creator><![CDATA[Dana C]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 21:41:12 GMT</pubDate>
            <atom:updated>2021-08-11T21:41:12.824Z</atom:updated>
            <content:encoded><![CDATA[<p>What are the differences from Object.create() and Object.assign()? Let’s explore!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRY5PRvT9a8yQ-lWYWau8g.png" /><figcaption>Object.create() vs. Object.assign()</figcaption></figure><ol><li>Test for prototypal relationships</li></ol><p>Object.create</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let menno = Object.create(dog);<br>Object.getPrototypeOf(menno) === dog; <em>// true</em><br>dog.isPrototypeOf(menno); <em>// true</em></pre><p>Object.assign</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let menno = Object.assign({}, dog);<br>Object.getPrototypeOf(menno) === dog; <em>// false</em><br>dog.isPrototypeOf(menno); <em>// false</em></pre><p>2. Adding new property or method to a newly created object</p><p>Object.create</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let menno = Object.create(dog, {<br>  jumps: {<br>    value: function () {<br>      console.log(&#39;jumping!&#39;);<br>    },<br>    writable: false,<br>  },<br>});</pre><pre>menno.jumps(); <em>// jumping</em><br>menno.barks(); <em>// woof woof</em></pre><p>Object.assign</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let menno = Object.assign({}, dog, {<br>  jumps() {<br>    console.log(&#39;Jumping!&#39;);<br>  }<br>});</pre><pre>menno.jumps(); <em>// jumping</em><br>menno.barks(); <em>// woof woof</em></pre><p>3. Access to methods up the prototypal chain</p><p>Object.create</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let jackie = Object.create(dog);</pre><pre>Object.defineProperties(jackie, {<br>  swims: {<br>    value: function() {<br>      console.log(&#39;swimming swimming&#39;);<br>    },<br>    writable: false;<br>  },<br>});</pre><pre>let menno = Object.create(jackie);<br>menno.swims(); <em>// swimming swimming</em><br>menno.barks(); <em>// woof woof</em></pre><p>Object.assign</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let jackie = Object.create(dog);</pre><pre>let menno = Object.assign({}, jackie);</pre><pre>menno.barks(); <em>// TypeError, menno.barks is not a function</em></pre><p>4. Combine the deep cloning functionalities of Object.create() with the flexibility of Object.assign()</p><p>Object.assign(Object.create(obj), ...sourceObjs)</p><pre>let dog = {<br>  barks() {<br>    console.log(&#39;woof woof&#39;);<br>  }<br>}</pre><pre>let menno = Object.assign(Object.create(dog), {<br>  swims() {<br>    console.log(&#39;swimming swimming&#39;);<br>  }<br>});<br>menno.swims(); <em>// swimming swimming</em><br>menno.barks(); <em>// woof woof</em></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14bfef43df9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four object creation patterns in Javascript]]></title>
            <link>https://medium.com/@danacc/four-object-creation-patterns-in-javascript-422e00c51fab?source=rss-7e626f3316e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/422e00c51fab</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dana C]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 21:34:33 GMT</pubDate>
            <atom:updated>2021-08-11T21:34:33.601Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a summary of the various patterns in JS Object Creation, and performing various actions on those objects.</p><p>For each of the patterns below, we want to perform the following functions:</p><ul><li>Object or function creation</li><li>Extending the object or function</li><li>Creation of subclass with properties from multiple objects or functions</li></ul><p><strong>Factory Pattern</strong></p><p>Creating the factory function:</p><pre><em>function</em> Dog(<em>name</em>, <em>age</em>) {<br>  return {<br>    name,<br>    age,</pre><pre>    barks() {<br>      console.log(`${this.name} barks!`);<br>    }<br>  }<br>}</pre><pre><em>let</em> menno = Dog(‘menno’, 12);<br>console.log(menno.name); // menno<br>console.log(menno.age); // 12<br>menno.barks(); // menno barks!</pre><p>Extending the Dog function:</p><pre><em>function</em> JackRussell(<em>name</em>, <em>age</em>) {<br>  return <em>Object</em>.assign(Dog(name, age),<br>    jumps() { console.log(`${this.name} jumps!`)<br>    },<br>  });<br>}</pre><pre><em>let</em> bram = JackRusell(‘bram’, 10);<br>console.log(bram.name); // bram<br>console.log(bram.age); // 10<br>bram.barks(); // bram barks!<br>bram.jumps(); // bram jumps!</pre><p>Mixing the properties of a Jack Russell with that of a Golden Retriever:</p><pre><em>function</em> GoldenRetriever(<em>name</em>, <em>age</em>) {<br>  return <em>Object</em>.assign(Dog(name, age), {<br>    swims() {<br>      console.log(`${this.name} swims!`);<br>    }<br>  })<br>}</pre><p>Now creating a mix of GoldenRussell with properties from both Retriever and Jackie:</p><pre><em>function</em> GoldenRussell(<em>name</em>, <em>age</em>) {<br>  return <em>Object</em>.assign(JackRussell(), GoldenRetriever(name, age));<br>}</pre><pre><em>let</em> bruno = GoldenRussell(‘bruno’, 1);<br>console.log(bruno.name); // bruno<br>console.log(bruno.age); // 1<br>bruno.barks(); // bruno barks!<br>bruno.jumps(); // bruno jumps!<br>bruno.swims(); // bruno jumps!</pre><p><strong>Constructor Pattern</strong></p><p>Creating the constructor function:</p><pre><em>function</em> Dog(<em>name</em>, <em>age</em>) {<br>  this.name = name;<br>  this.age = age;<br>  this.barks = <em>function</em>() {<br>    console.log(`${this.name} barks!`);<br>  }<br>}</pre><pre><em>let</em> menno = new Dog(‘menno’, 11);<br><em>let</em> luna = <em>Object</em>.create(menno);<br>menno.name;<br>menno.age;<br>menno.barks();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*QSrAA4CY2gCr3ctRPY59oQ.png" /><figcaption>Method is added in the constructor function itself</figcaption></figure><p>Alternatively:</p><pre><em>function</em> Dog(<em>name</em>, <em>age</em>) {<br>  this.name = name;<br>  this.age = age;<br>}</pre><pre><em>Dog</em>.prototype.barks = <em>function</em>() {<br> console.log(`${this.name} barks!`)<br>}</pre><pre><em>function</em> Husky() {}<br><em>Husky</em>.prototype = new Dog(name, age);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*8TTW4Kqy1jpaBqgBNXB5kw.png" /><figcaption>Method is added on the function prototype</figcaption></figure><p>Mixing the constructor pattern with OOLO should result in the same outcome:</p><pre><em>function</em> Dog() {};<br><em>Dog</em>.prototype.barks = <em>function</em>() {<br>  console.log(‘it barks!’);<br>}</pre><pre><em>let</em> jackie = new Dog();<br><em>let</em> menno = <em>Object</em>.create(jackie);</pre><p>Checking for prototypal inheritance:</p><pre>Dog.isPrototypeOf(jackie); // false<br><em>Dog</em>.prototype.isPrototypeOf(jackie); // true<br><em>Dog</em>.prototype.isPrototypeOf(menno); // true<br>jackie.isPrototypeOf(menno); // true</pre><pre>// Checking for use of instanceof<br>jackie instanceof Dog; // true<br>menno instanceof Dog; // true<br>menno instanceof jackie; // TypeError</pre><p>Extending the Dog function:</p><pre>jackie.jumps = <em>function</em>() {<br>  console.log(‘it jumps!’)<br>}</pre><pre><em>Dog</em>.prototype.swims = <em>function</em>() {<br>  console.log(‘it swims!’)<br>}</pre><pre><em>Object</em>.defineProperties(jackie, {<br>  eats: {<br>    value: <em>function</em>() {<br>      console.log(‘it eats!’);<br>    },<br>    writable: true,<br>  },<br>})</pre><pre>jackie.__proto__.sleep = <em>function</em>() {<br>  console.log(‘it sleeps!’);<br>}</pre><pre><em>Object</em>.getPrototypeOf(jackie).run = <em>function</em>() {<br>  console.log(‘it runs!’);<br>}</pre><pre>menno.jumps(); // it jumps!<br>menno.swims(); // it swims!<br>menno.eats(); // it eats!<br>menno.sleep(); // it sleeps!<br>menno.run(); // it runs!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*MbaHiC9fsWJd46zKA105PQ.png" /><figcaption>Effect of adding methods in different ways</figcaption></figure><p>Mixing in other methods:</p><pre><em>function</em> Wolf() {<br>  this.hunts = <em>function</em>() {<br>    console.log(‘it hunts!’);<br>  }<br>}</pre><pre><em>let</em> wolf = new Wolf();</pre><pre><em>function</em> Husky() {<br>  return <em>Object</em>.assign(wolf, <em>Dog</em>.prototype);<br>}</pre><pre><em>let</em> husky = new Husky();<br>husky;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*MBmPERUaSwERw9IOUJTxxQ.png" /><figcaption>Object with mixed in methods</figcaption></figure><p>Let’s use inheritance to share methods across different constructor functions.</p><pre><em>function</em> Dog(<em>name</em>, <em>age</em>) {<br>  this.name = name;<br>  this.age = age;<br>  this.barks = <em>function</em>() {<br>    console.log(‘it barks!’)<br>  }<br>}</pre><pre><em>function</em> Husky(<em>name</em>, <em>age</em>) {<br>  Dog.call(this, name, age);<br>  this.hunts = <em>function</em>() {<br>    console.log(‘it hunts!’)<br>  }<br>}</pre><pre><em>let</em> lars = new Husky(‘lars’, 8);<br>lars.barks(); // it barks!<br>lars.hunts(); // it hunts!<br><em>Object</em>.getPrototypeOf(lars) === <em>Husky</em>.prototype; // true<br><em>Object</em>.getPrototypeOf(lars) === <em>Dog</em>.prototype; // false<br>lars instanceof Husky; // true<br>lars instanceof Dog; // false</pre><p>Note that after Dog.call() is applied in the new Husky function, any new Husky objects now has access to pre-existing objects in the Dog class.</p><p>But what if we add another method to Dog?</p><pre><em>let</em> menno = new Dog(‘menno’, 11);</pre><pre><em>Dog</em>.prototype.swims = <em>function</em>() {<br>  console.log(‘it swims!’);<br>}</pre><pre>menno.swims(); // it swims!<br>lars.swims(); // TypeError</pre><p>The fix is to ensure Husky is inheriting from the Dog prototype.</p><pre><em>Husky</em>.prototype = <em>Object</em>.create (<em>Dog</em>.prototype);<br><em>Husky</em>.prototype.constructor = Husky;<br><em>let</em> lars = new Husky(‘lars’, 8);<br>lars.swims(); // it swims!</pre><p>So the reason for setting the prototypal chain is so that the new object can always inherit from the function, and not merely accessing the methods that it was originally called with (the Dog.call()).</p><p><strong>ES6 Pattern using class</strong></p><pre><em>class</em> Dog {<br>  <em>constructor</em>(<em>name</em>, <em>age</em>) {<br>    this.name = name;<br>    this.age = age<br>  };</pre><pre>  barks() {<br>    console.log(‘it barks!’);<br>  };<br>}</pre><pre><em>let</em> menno = new Dog(‘menno’, 11);<br>menno.barks();</pre><pre><em>class</em> Husky extends <em>Dog</em> {<br>  hunts() {<br>    console.log(‘it hunts!’);<br>  }<br>}</pre><pre><em>let</em> lars = new Husky(‘lars’, 8);<br>lars.hunts();<br><em>Husky</em>.prototype.isPrototypeOf(lars);<br><em>Dog</em>.prototype.isPrototypeOf(lars);</pre><p>Adding mixins from multiple classes, Wolfcat gets properties from both Husky and Cat.</p><pre><em>class</em> Cat {<br>  <em>constructor</em>(<em>name</em>, <em>age</em>) {<br>    this.name = name;<br>    this.age = age;<br>  };</pre><pre>  purrs() {<br>    console.log(this.name + ‘ purrs!’);<br>  };</pre><pre>  plays() {<br>    console.log(this.name + ‘ plays!’);<br>  };<br>};</pre><pre><em>class</em> Wolfcat extends <em>Husky</em> {<br>  <em>constructor</em>(<em>name</em>, <em>age</em>) {<br>    super (name, age);<br>  }<br>}</pre><pre>for (<em>let</em> method of <em>Object</em>.getOwnPropertyNames(<em>Cat</em>.prototype).filter(<em>item</em> <em>=&gt;</em> typeof <em>Cat</em>.prototype[item] === ‘function’ &amp;&amp; item !== ‘constructor’)) {<br>  <em>Wolfcat</em>.prototype[method] = <em>Cat</em>.prototype[method];<br>}</pre><pre><em>let</em> feline = new Wolfcat(‘feline’, 2);<br>feline.barks(); // it barks!<br>feline.hunts(); // it hunts!<br>feline.purrs(); // it purrs!<br>feline instanceof Husky; // true<br>feline instanceof Wolfcat; // true<br>feline instanceof Cat; // false<br><em>Dog</em>.prototype.isPrototypeOf(feline); // true<br><em>Husky</em>.prototype.isPrototypeOf(feline); // true<br><em>Cat</em>.prototype.isPrototypeOf(feline); // false<br><em>Object</em>.getPrototypeOf(feline) === <em>Wolfcat</em>.prototype; // true</pre><p><strong>OLOO Pattern</strong></p><pre><em>let</em> Dog = {<br>  init: <em>function</em>(<em>name</em>, <em>age</em>) {<br>    this.name = name;<br>    this.age = age;<br>    return this;<br>  },</pre><pre>  barks() {<br>    console.log(‘it barks!’);<br>  }<br>}</pre><pre><em>let</em> luna = <em>Object</em>.create(Dog).init(‘luna’, 8);</pre><pre><em>let</em> Jackie = <em>Object</em>.create(Dog, {<br>  jumps: {<br>    value: <em>function</em>() {<br>      console.log(‘it jumps!’);<br>    },</pre><pre>    writable: false,<br>    enumerable: true,<br>  }<br>});</pre><pre><em>let</em> menno = <em>Object</em>.create(Jackie).init(‘menno’, 11);</pre><pre><em>let</em> Fish = {<br>  swims() {<br>    console.log(‘it swims!’);<br>  }<br>}</pre><pre><em>let</em> Retriever = <em>Object</em>.assign(<em>Object</em>.create(Dog), Jackie, Fish);<br><em>let</em> lulu = <em>Object</em>.create(Retriever).init(‘lulu’, 7);<br>lulu.swims(); // it swims<br>lulu.jumps(); // it jumps<br>lulu.barks(); // it barks</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422e00c51fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does the Internet work?]]></title>
            <link>https://medium.com/@danacc/how-does-the-internet-work-3fadbfecc7b4?source=rss-7e626f3316e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fadbfecc7b4</guid>
            <category><![CDATA[tcp-ip]]></category>
            <category><![CDATA[osi-model]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Dana C]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 18:55:26 GMT</pubDate>
            <atom:updated>2021-08-11T18:55:26.457Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Or, how do bits and bytes of data show up on your screen? My own exploration of networking principles.</strong></p><p>This is just another day. You wake up with a cup of coffee and scan your inbox, chat apps and news sites for the latest round of updates. Once the coffee kicks in and you’ve stretched out and ready to go, you hop on Zoom for a team meeting, while taking notes on a Google doc that can be shared later on.</p><p>At lunch, you put on a pair of running shoes and turn on some Spotify for a quick workout. In between working sessions on the afternoon, you jump in a couple of Discord servers with your gamer friends to plan out the next play session.</p><p>Dinner time rolls around, you grab your favourite beverage, fire up a Hangout session, and start your Netflix watching party with a couple of your best pals.</p><p>None of these activities would’ve been possible without the existence of the Internet. Or is it the web? But what are these things, and do they enable these incredible experiences at your fingertips?</p><p>First and foremost, what is the Internet?</p><p>At its core, the Internet is a <strong><em>network of networks</em></strong> that is linked by a plethora of physical infrastructure. This ultimate network connects all kinds of local area networks or wide area networks, whether private, public, business, academic, or government. And this physical infrastructure of local networks carry all kinds of electronic data like text, images, sounds, that are delivered to the end client like yourself, through the web browser.</p><p>So here it is in a nutshell:</p><ul><li>The Internet is a network of smaller networks.</li><li>The Internet is connected through physical infrastructure like fibre-optic cables and wireless signals.</li><li>The Internet allows electronic data to travel through its underlying infrastructure.</li><li>The service is the web, the infrastructure is the Internet. Or, think of it another way, the software is the web, the hardware is the Internet. Alternatively, road is the Internet, and traffic is the web. But it’s not the only kind. There can be other forms of traffic in the form of email, FTP, instant messaging.</li><li>The web represents the information system accessible through the physical infrastructure, the Internet.</li><li>We access information made available on the web through its identifier, the URL.</li><li>We interface with web content through web browsers.</li></ul><p>Now that we have established the relationship between the Internet versus the web (or in other words, infrastructure versus service, hardware versus software, road versus traffic), the next question becomes, how does traffic move through the road?</p><p>There’s the vague idea that content exists somewhere far off, in a place that you might have heard of that houses something called servers. So how does that intangible entity called data somehow end up on your screen?</p><p>In order to answer that question satisfactorily, we need to introduce two chunks of information that will give us some grounding in mental models. One is the concept of <strong>protocols</strong>, the other is the concept of <strong>networking layers</strong>.</p><p>Protocols refer to rules that govern how data is exchanged over the Internet. Yes, there’s a lot of them. And the reason why all of them are necessary, is because we need to address a matrix of different issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*sCUEbdKe3YiNKtAOATalSQ.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Internet_Protocol">Wikipedia</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhA0BRGMqh6xD-AORFRVaw.png" /><figcaption>Different protocols address different communication or user case needs</figcaption></figure><p>On a broad level, we can say that protocols govern how messages and sent and received. But on a more granular level, we can distinguish the intent of those protocols into two distinct categories.</p><p>One broad category help us establish syntactic rules regarding the message transfer protocol, the other category govern the rules around how messages are transferred. That’s to say, we want to distinguish rules that govern how the messages are structured (syntactically, what is in this message? Do you need an address, proper greetings, acknowledgement of receipt, and a message body?), to the mechanics of message flow (do you need a two-way conversation or will a one-way monologue do?).</p><p>One example of the syntactical difference we experience in communication settings could be the difference between how we speak at a party versus how we speak in a courtroom. In a party setting, there’s no need to formally address any new entrants to the party, new need to formally address anyone when you want to ask a question, and no formal end to a conversation — people just interweave in and out of conversations. In a court room, on the other hand, needs to be very specific regarding her intent to speak. She needs to be very specific about the party she wishes to address and the question she might want to ask.</p><p>On rules regarding message transfer, a student is faced with a very different communication style depending on whether she’s sitting in a lecture versus a lab. In a classroom, the teacher engages in mostly one-way communication. But in a lab session, the TA commits to two-way communication, ensuring the information is well-received before proceeding onto the next topic.</p><p>With these two specific concerns in mind, a slew of protocols are developed.</p><p>Now back to the second concept we want to explore, and that is to use the analogy of layers to represent the different aspects of network communication. They are known as the <strong>OSI </strong>and the <strong>TCP/IP</strong> model.</p><p>OSI stands for <strong>Open Systems Interconnection Model</strong>, and is a reference/guideline developed by the ISO to delegate responsibilities and to understand the communication process. Each layer represents the specific function they perform, for example: physical addressing, logical addressing, encryption, or compression.</p><p>TCP/IP stands for Transmission Control Protocol / Internet Protocol Model: each layer represents the scope of communication it’s responsible for. For example, is it responsible for action within a LAN, or between networks?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xdJnosdnPVb4wriUljG5A.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Protocol_stack">Wikipedia</a></figcaption></figure><p>So how exactly does the OSI model explain how data moves from A to B through various layers?</p><p>Let’s first broadly group the various layers of the OSI model. The top four layers from the OSI layer deal with data coming out of the computer, while the bottom three layers deal mostly with data that will interact with devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koPbsVwhMfuDweuT8GVE9g.png" /><figcaption>OSI and TCP/IP protocol with their respective PDUs and protocols</figcaption></figure><p><strong>Top three layers</strong></p><p>The three top layers has one responsibility: to make data available for the Transport layer. The PDU (protocol data unit) is binary data at this point. The lack of distinguishing features when it comes to data transport is the reason why we call the Internet the converging network, it’s where all the data converges on the same network.</p><p>When we are on the Application layer, we identify the binary data by file extension (e.g. jpeg, exe). This is an interface for the network. A software developer that develops a web browser, would need to agree to the application level protocol called the HTTP protocol. We also have identification called addresses to identify the service. HTTP is an example of an application layer protocol (DNS, FTP, SMTP), and work with the user to prepare data to be ready for the next layer.</p><p>The next layer, the Presentation layer, is responsible for encoding (ASCII), encrypting (SSL/TCL), and compressing (gzip) data for the next layer.</p><p>The layer down from the Presentation layer is the Session layer. This layer takes care of dialogue management and keeps the connection alive.</p><p><strong>Transport Layer</strong></p><p>One layer down, we get Transport. The Transport layer is responsible for getting the segment to the right application (client) or service (server). The protocol that defines a segment is called TCP. If a PDU is produced, a protocol needs to exist to specify how PDU is produced. Time is sacrificed for relevance in the TCP protocol. Another protocol here is UDP.</p><p>To understand why Transport layer does what it does, we need to be aware of what a user does when she interacts with a device. She is likely working with multiple applications at the same time, e.g. email, Torrent, browser. The Transport layer is going to identify what application is making requests, and what services receive them.</p><p>We identify them through port addresses, with source and destination addresses. On this layer, we take the binary data formed from the top three layers and create a PDU. Each data PDU at this layer will have a source and destination address. The PDU for the Transport layer is called either a Segment, or a Datagram, depending on which Protocol it’s using.</p><p>At this point, the data is split into multiple segments, and the Transport layer is responsible for moving the segments in the most efficient and reliable manner. Segments are dispersed over multiple pathways. The segments are numbered and are put back together.</p><p>Security is also built into the protocol itself, because it’s hard for one person to get the all pieces of the data.</p><p>Those segments will have sequence numbers and acknowledgement numbers, where a server knows what’s been received and what’s coming next. Port addresses are also in this header: source and destination addresses.</p><p>At this level, there’s a number of different protocols that can be chosen. TCP chooses reliability over speed, but that might not be suitable when say a torrent or a video is streamed. In that case, a more unreliable but speedy delivery method called UDP is chosen. The sizes of the segment could be bigger and the header smaller.</p><p>To choose one protocol over the next means that we need to make a choice between reliability and speed. When we look at the trade-off, we need to acknowledge that for example, delivery is either going to be reliable, or not. To achieve maximal security, we will sacrifice speed. To get speed, we need to give up some of the benefits that come with reliability, for example, same order delivery, reliable communications, and mechanism for failure detection (flow control).</p><p>This layer is also where the concept of multiplexing comes in. Segmentation is used to not only disperse messages across several connections, it also allows multiple people to use the connection simultaneously. Computer looks like it’s multi-tasking even when it’s not. Most connections can’t handle parallel connections, we multiplex the conversation, taking segments from different connections and weave them together, so it looks like everyone’s using the same connection.</p><p><strong>Down to the Physical Layers</strong></p><p>While the Transport layer identifies applications and services receiving it segments, we need a mechanism to know which pathway a segment needs to travel to. This is done by the Network layer.</p><p>When segments are distributed across the network, the Network layer routes it along the way through a router. The segment is encapsulated with a header attached, and the PDU at this point becomes a packet. The protocol responsible for the specification of this PDU is called an IP protocol, where a source and destination address are added to the header.</p><p>Compared to the Transport Layer, where addresses are used to identify application and services, on the Network layer, IP is used to identify the device connected on the network.</p><p>What’s the difference between a packet and a segment? Packet has information that identifies the end device. The sender and receiver. In this header, there’s an address. The most common addressing mechanism used at the moment is the IPv4.</p><p>Although it might seem as though IP is the only protocol active on the Network layer, that’s not true. There’s also AppleTalk, NetValue, IPx, ConnectionLess Network Services. So why is IP protocol the most prevalent? Because it’s an open protocol. More people are willing to adopt a protocol if it’s open.</p><p>The packet is now passed down to the Data Link Layer, where a frame is produced, along with a header and trailer. This is the only layer with a trailer as well as a header.</p><p>At this point, the Data Link layer and Physical layers start converting the logic from the top layers down to the physical world of devices. This is the last layer where encapsulation occurs.</p><p>To recap, port addresses identify the application and service, IP addresses identify the sender and receiver, and at the Data Link layer, MAC address are used to identify the devices. Note that MAC addresses are relatively unchangeable. Ethernet protocol is responsible for this layer, and requires physical source and destination addresses. It also attaches both a header and trailer to the payload, which specifies, when a frame begins and ends. The trailer determines if the frame has arrived with error.</p><p>But how do we know whether the data travelling through a wire is valid or not? The protocol knows how a pattern begins and how it ends. When the protocol encounters a specific pattern that’s not natural (think about how we can codify claps with frequency and a specific rhythm and count), that’s how we know when a PDU begins or end transmission.</p><p>Now the data is ready for physical transmission, where all the bits are taken and carried into a signal. How does data get transmitted? Either through pulses of electricity through a wire, or pulses of electricity that generate radio waves in the case of wifi.</p><p>In summary, the communication process goes in both directions. Going down the stack requires encapsulation, going up the stack results in decapsulation.</p><p><strong>Same actors, slightly different angle of looking at the problem</strong></p><p>The same process can be explained by the TCP/IP model, only with a slightly different focus. While OSI model was developed based on the function each layer was produced, the TCP/IP model is mapped from the corresponding protocol that governs each step of the communication process.</p><p>The top layer is the application layer, which takes care of the software information side. HTTP is the protocol that governs the data output from this level. Regardless of how communication takes place, the subject of topic needs to be identified, which is where the application and services need to be specified.</p><p>The Transport layer produces segments and is governed by TCP or UDP protocol.</p><p>The Internet layer produces a packet and abides by the IP protocol.</p><p>And the last layer is called the Link layer and governed by the Ethernet protocol, which includes the Data and Physical layers from the OSI model, where the PDU is also called a frame.</p><p>Now that we have a good understanding of how data travels through from client to server, stay tuned for how features built into some of those protocols ensure secure connection and error-free delivery, in the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fadbfecc7b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Method arguments in Ruby]]></title>
            <link>https://medium.com/@danacc/method-arguments-in-ruby-b14ff7be7bf0?source=rss-7e626f3316e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14ff7be7bf0</guid>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dana C]]></dc:creator>
            <pubDate>Sun, 02 Dec 2018 00:00:24 GMT</pubDate>
            <atom:updated>2023-09-15T06:34:28.963Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby allows for great flexibility in how arguments can be passed into a method.</p><p>There are 3 categories of arguments that get passed into a method, depending on how you look at them:</p><ol><li>Required arguments</li><li>Arguments with default values</li><li>Optional arguments</li></ol><p>Ex1: required arguments are pretty straightforward</p><pre>def any_old_method(param)<br>   param<br>end<br><br>any_old_method(‘Hi there!’)     #=&gt; ‘Hi there!</pre><p>Ex2: args with default value, note the default value is optional</p><pre>def method_with_default_value (a, b = 2018)<br>  &quot;It&#39;s #{a} in #{b}.&quot;<br>end<br><br>method_with_default_value(&#39;December’)          #=&gt; “It’s December in 2018&quot;<br>method_with_default_value(&#39;December&#39;, 2019)    #=&gt; “It’s December in 2019&quot;</pre><p>Ex3: the spat operator makes either all arguments optional …</p><pre>def any_num_of_params(*args)<br>    args<br>end<br><br>any_num_of_params(1, 2, 3, 4) #=&gt; [1, 2, 3, 4]</pre><p>Ex4: or, a sub-set of the parameters optional. Some are required, the rest are coerced into an array</p><pre>def any_num_of_params(required_arg, *optional_arg)<br>  p required_arg<br>  p optional_arg<br>end<br><br>any_num_of_params(1, 2, 3, 4) #=&gt; 1 [2, 3, 4]</pre><p>Ex5: an optional parameters situation, where changing the parameter list of a superclass won’t affect those in the subclass anymore. The method accepts any arguments but does nothing with them. A practical use would be in combo with the super keyword.</p><pre>class A<br>  def method_across_classes(param1, param2)<br>    puts param1<br>    puts param2<br>  end<br>end<br><br>class B &lt; A<br>  def method_across_classes(*)<br>    super<br>  end<br>end<br><br>subclass_object = B.new<br>subclass_object.method_across_classes(&#39;param 1&#39;, &#39;param 2’) #=&gt; param 1 param 2</pre><p>Ex6: when types of arguments are mixed and matched, look at the progression of this example.</p><p>We intersperse method parameters that are required, optional, or default. And in the method invocation, we provide a variety of arguments that satisfies at least the “required” number of arguments.</p><p>Note the categories of parameters here: 1. required -&gt; a, b, d, 2. optional: <em>c, *</em> d. <em>c turns rest of input into an array, while *</em> d catches the hashes</p><pre>def testing(a, b = 1, *c, d: 1, **x)<br>  p a,b,c,d,x<br>end<br><br># case 1<br>testing(‘a’)<br>#=&gt; ‘a&#39; 1 [] 1 {} <br># both b and d return their default values, a is passed in, and there’s no optional values for c or x to collect<br><br># case 2<br>testing(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;)<br>#=&gt; ‘a&#39; ‘b’ [‘c’] 1 {} <br> # a b, d are the required values and both are passed in; d takes on the default value, and the argument ‘c’ is collected by *c<br><br># case 3<br>testing(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, d: 2, x: 1)<br>#=&gt; ‘a&#39; ‘b’ [‘c’, ‘d&#39;] 2 {: x= &gt;1}<br># note the syntax for parameter are method(required, default, optional arrays, default, optional hashes)<br># switch the hashes and the arrays<br><br># case 4<br>change the method definition slightly to:<br><br>def testing(a, b = 1, *c, d, **x)<br>  p a,b,c,d,x<br>end<br><br>testing(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, d, x: 1)<br>#=&gt; ‘a&#39; ‘b’ [‘c’, ‘e’, ‘f’] ‘g’ {:d =&gt; 2, : x= &gt;1}<br># my interpretation is that the *c is collecting all the optional value arguments passed in, until it meets the optional value arguments gathered by **x, then the string ‘g’ is passed in as the required parameter d<br><br># case 5<br># again a slight change to the method definition <br><br>def testing(a, b = 1, d = 1, *c, **x)<br>  p a, b, d, c, x<br>end<br><br>testing(&#39;a&#39;, &#39;b&#39;, ‘c&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, d:2, x:1)<br>#=&gt; ‘a&#39; ‘b’, ‘c’, [‘e’, ‘f’, ‘g’] {:d =&gt; 2, : x= &gt;1}<br># in this case, a passes in a required parameter, b and d pass in optional value parameters (both have default values assigned), *c collects array [e, f, g], and the hash collects the rest<br><br># case 6a<br># what if we define the default value parameter after the optional value parameter?<br><br>def testing(a, b = 1, *c, d = 1, **x)<br>  p a, b, d, c, x<br>end<br><br>testing(&#39;a&#39;, &#39;b&#39;, ‘c&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, d:2, x:1)<br>#=&gt; syntax error, unexpected &#39;=&#39;, expecting &#39;)&#39;<br># default value parameter must occur before optional value parameter<br><br># case 6b<br># unless the default value points to a hash<br><br>def testing(a, b = 1, *c, d: 1, **x)<br>  p a, b, d, c, x<br>end<br><br>testing(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, d: 2, x: 1)<br>#=&gt; ‘a&#39; ‘b’, 2, [‘c’, ‘e’, ‘f’, ‘g’] {: x= &gt;1}</pre><p><em>Originally published at </em><a href="https://blog.dotdana.com/method-arguments-in-ruby/"><em>https://blog.dotdana.com</em></a><em> on December 2, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14ff7be7bf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A deeper look at Ruby’s Enumerable#reduce]]></title>
            <link>https://medium.com/@danacc/a-deeper-look-at-rubys-enumerable-reduce-36b33a0cc6d1?source=rss-7e626f3316e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b33a0cc6d1</guid>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dana C]]></dc:creator>
            <pubDate>Thu, 29 Nov 2018 00:00:53 GMT</pubDate>
            <atom:updated>2023-09-15T06:31:36.975Z</atom:updated>
            <content:encoded><![CDATA[<p>When first learning about collections and the Enumerable module in Ruby, like most beginners, I focused on understanding and applying #each, #map, and #select. It’s not until months down the road, while browsing problem solutions by Rubyists, that I began to discover the power of the #reduce method and began digging deeper.</p><p>In this post, I want to articulate my understanding of the method and its applications at this moment. I hope to continue updating my mental model of both the method itself, and the paradigm that it represents (Map/Reduce in functional programming).</p><h3>Why #reduce?</h3><p>I began this exploration by first trying to understand the problem #reduce is built to solve.</p><p>Enumerable#reduce, like the rest of the Enumerable methods, work with collections.</p><p>But unlike #each or #map, where a collection is returned at the end, #reduce performs a different kind of function over a collection. True to name, it “reduces”, or accumulates elements of the collection to a single value based on a binary operation, and returns one value at the end.</p><h3>#reduce syntax</h3><p>At first glance, #reduce seems to work with the same type of syntax as other members of the Enumerable class.</p><p>Let’s compare #reduce with #map for the most basic usage.</p><p>This is how a #map method works its way across a collection: the collection takes an enumerable object, in this case an array, and executes the block by passing in each element as an argument. The result of evaluating the block is returned as an array.</p><pre>(5..10).map { |num| num * 2 }<br>#=&gt; [10, 12, 14, 16, 18, 20]</pre><p>The most basic use of #reduce is its go-to use of “reducing” an array of elements with a block.</p><pre>(5..10).reduce { |sum, n| sum + n }<br>#=&gt; 45</pre><p>This looks close enough to a #map function, the only difference being that there are two elements passed in as argument for each step of the collection. We’ll look at those in detail in a sec, but in the meantime. we’ve also seen #reduce written in shorthand like this, without a block.</p><pre>(1..5).reduce(1, &amp;:*)<br>#=&gt; 120</pre><p>Or like this, without the 0 (accumulator).</p><pre>(1..5).reduce(&amp;:*)<br>#=&gt; 120</pre><p>Or like this, without even the ampersand.</p><pre>(1..5).reduce(:*)<br>#=&gt; 120</pre><p>So what is essential, and what is superfluous, when it comes to using the #reduce method?</p><p>The Ruby documentation mentions three different inputs, which I’m going to refer to as accumulator(initial), operator(sym), and block. When passed in as arguments, memo refers to the accumulator, and obj is the current value iterated over.</p><pre>reduce(initial, sym) → obj<br>reduce(sym) → obj<br>reduce(initial) { |memo, obj| block } → obj<br>reduce { |memo, obj| block } → obj</pre><p>At the beginning of a method, we have three values that can be passed in: an accmumulator that is the starting value of the series of binary operation performed over a collection, an operator that defines the operation to be performed, and a block that can further define what needs to be performed.</p><p>We can play around with the method by reading the error messages it throws.</p><ol><li>Provide no block and no operator.</li></ol><pre>(1..5).reduce<br>#=&gt; no block given</pre><p>The error message tells us that a block is expected in this case.</p><p>2. Provide only the accumulator, no operator or blocks.</p><pre>(1..5).reduce(1)<br>#=&gt; 1 is not a symbol nor a string</pre><p>Error message suggests in the absence of a block, it’s expecting either a symbol or a string to act as the operator.</p><p>3. Pass in a method #to_f to where a symbol is expected.</p><pre>(1..5).reduce(:to_f)<br>#=&gt; wrong number of arguments (given 1, expected 0)</pre><p>This confirms that the method only accepts a certain type of method, and #to_f isn’t one of them.</p><p>4. What if we try to pass in an operator and a block at the same time?</p><pre>(1..5).reduce(&amp;:*) {|memo, obj| memo += obj}<br>#=&gt; both block arg and actual block given</pre><p>It looks like we can’t pass in both an operator and a block. This could be because the &amp; turns the :+ method into a block, which then conflicts with the block that’s also getting passed in.</p><p>But what if we change the code slightly to the following:</p><pre>(1..5).reduce(1, :*) {|memo, obj| memo += obj}<br>#=&gt; 120</pre><p>By specifying the accumulator value, and leaving the method as a symbol, we can actually pass in both an operator and a block at the same time.</p><p>Which command will the program run? The operator or the block?</p><pre>(1..5).reduce(1, :*) {|memo, obj| memo += obj}<br>#=&gt; 120</pre><p>It looks like the operator takes precedence over the block.</p><p>After all that spilled ink, it looks like #reduce method can show up in one of four flavours:</p><ol><li>Takes a block and an accumulator (1..5).reduce(1) { |memo, obj| memo *= obj }</li><li>Takes no parameters, only block (1..5).reduce { |memo, obj| memo *= obj }</li><li>Takes an operator and an accumulator (1..5).reduce(1, :*), or (1..5).reduce(1, &amp;:*)</li><li>Takes an operator only (in symbol or block form) (1..5).reduce(:*), or (1..5).reduce(&amp;:*) *5. It accepts both an operator and a block, if the operator is passed in as a symbol, and processes the operator. But why?</li></ol><p>Moving on, let’s see how it can be used!</p><h3>Using #reduce to solve problems</h3><p>TL;DR: #reduce is particulalry effective when it comes to accumulating values across an array (accumulating not just in a numerical sense, but also to compare and select other input types such as a string), and is also handy when we want to dynamically build a new object from a collection based on another set of conditions.</p><ol><li>Let’s see how #reduce can also be used to perform an iterative action if it involves comparison, or accumulation.</li></ol><p>Problem: Given an array of words, find the longest word.</p><p>Solution using #reduce:</p><pre>%w(cat mouse donkey).reduce do |memo, word| <br>    memo.length &gt; word.length ? memo : word<br>end<br>#=&gt;&quot;donkey&quot;</pre><p>Combined with a ternary operator, #reduce stores the sought after value in its memo parameter, returning the value at the end.</p><p>Problem: Given a string, make it shout by duplicating every vowel 5 times.</p><p>Solution using #reduce:</p><pre>&quot;How are you?&quot;.chars.reduce { |memo, char| %w[a e i o u y].include?(char) ? memo + char * 5 : memo + char }<br>#=&gt; &quot;Hooooow aaaaareeeee yyyyyooooouuuuu?&quot;</pre><p>Chained after a #char method, #reduce uses a ternary operator again to perform what’s passed in through the block.</p><p>2. We can also use #reduce to turn an array into a hash.</p><p>Problem: Given an array of letters like [a, b, c], return an array that shows each array element pointing to its ASCII equivalent. (Hint: make use of #ord and #update)</p><p>Solution using #reduce: Remember this is one of the ways Ruby processes #reduce: reduce(initial) { |memo, obj| block } → obj</p><pre>%w(a b c).reduce({}) {|memo, obj| memo.update(obj =&gt; obj.ord)}<br>#=&gt; {&quot;a&quot;=&gt;97, &quot;b&quot;=&gt;98, &quot;c&quot;=&gt;99}</pre><p>A hash is initialized as the accumulator, hash entries are added while working through the collection. Note that update is the same as #merge, and is used to update a hash.</p><pre>update(other_hash) → hsh<br>update(other_hash){|key, oldval, newval| block} → hsh</pre><p>We can achieve the same results with 1) map/each, and 2) each_with_object, is #reduce better or worse?</p><pre>hsh = {}<br>  %w(a b c).map do |item, num|<br>    hsh[item] = item.ord<br>  end<br>  hsh</pre><pre>hsh = {}<br>  %w(a b c).each do |item, num|<br>    hsh[item] = item.ord<br>  end<br>  ruby<br>end</pre><pre>%w(a b c).each_with_object(hsh = {}) do |(k, _), _|<br>  hsh[k] = k.ord<br>end<br>hsh</pre><p>3. Building an array as you go.</p><p>Problem: Given an array of integers, return an array of even numbers in string form.</p><p>Solution using #reduce:</p><pre>[*1..6].reduce([]) do |new_arr, el|<br>  new_arr &lt;&lt; el.to_s if el % 2 == 0<br>  new_arr<br>end<br>#=&gt; [&quot;2&quot;, &quot;4&quot;, &quot;6&quot;]</pre><p>Similar to the building-a-hash as you go example above, this time we are building an array conditional on another set of properties.</p><p>4. #reduce can also be deployed in a procedural Fibo problem. This is not the most intuitive use of #reduce, this is but a demonstration that it is possible.</p><p>Problem: Find the 10th Fibonacci number.</p><p>Solution: this can be solved in a variety of ways, #reduce is but one of them.</p><pre>p (0..8).reduce([0, 1]){|(a, b), _| [b, a+b]}.last<br>p (3..10).reduce([1, 1]){|(a, b), _| [b, a+b]}.last<br># =&gt; 55</pre><p>Using good old iteration.</p><pre>def fibo(n)<br>  a, b = 1, 1<br>  counter = 0<br>  while counter &lt;= n<br>    a, b = b, a+b<br>    counter += 1<br>  end<br>  a<br>end<br><br>p fibo(10)<br># =&gt; 55</pre><p>The same results with #recursion.</p><pre>def fibo(n)<br>    return n if (0..1).include?(n)<br>    fibo(n - 1) + fibo(n - 2)<br>end<br><br>p fibo(10)<br># =&gt; 55</pre><p>Using #each_with_object also does the job.</p><pre>def fibo(n)<br>  (n - 1).times.each_with_object([0, 1]) { |num, obj| p obj &lt;&lt; obj[-2] + obj[-1]}.last<br>end</pre><p><em>Originally published at </em><a href="https://blog.dotdana.com/a-deeper-look-at-Ruby%27s-Enumerable-reduce/"><em>https://blog.dotdana.com</em></a><em> on November 29, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b33a0cc6d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>