Using Ruby's .zip method to combine arrays

In Ruby, zip is a way to combine elements from two different arrays, albeit in a way that is slightly difficult to understand at first glance.

The documentation is a bit opaque, at least to my eyes, and the examples given take a bit of time to get your head around.

Let’s say you had an array of fruits that you wanted to distribute to your friends. You’re organised, so you have a list of your friends as well.

fruits = ["mango", "orange", "pomegranate"]
friends = ["Rob", "Mary", "Holly"]

Using multiple methods and loops, it’d be fairly trivial to conjure up something to combine these two into a new array, but luckily for us .zip exists to save the day.

will return:

[["Rob", "mango"], ["Mary", "orange"], ["Holly", "pomegranate"]]

This way everyone will know what fruit they’re getting.

Note that if one of the two arrays is longer / shorter than the other, the missing space(s) will be filled with nil values.

Pain: A Love Story

To go in the dark with a light is to know the light.

To know the dark, go dark. Go without sight,

and find that the dark, too, blooms and sings,

and is traveled by dark feet and dark wings.”

Wendell Berry

“We have been conditioned to think of the darkness as a place of danger, even of death. But the darkness can also be a place of freedom and possibility, a place of equality. For many, what is discussed here will be obvious, because they have always lived in this darkness that seems so threatening to the privileged. We have much to learn about unknowing. Uncertainty can be productive, even sublime.”

James Bridle

This is a story of pain. (The title sort of gives it away). As with babies or dreams, telling stories about pain is primarily of interest to the person directly involved. This is also not the story I thought I was writing. A few months back, I was starting to feel much better, as if the story that I began writing had changed. That one was a story of recovery, a story of lessons learned. It wasn't a story dictated from the trenches. Since then, I have been plunged back a few times into the experiential side of things. It's only a temporary setback, I keep telling myself. Nothing is permanent, especially pain.

For the past five years, I have living my days in varying levels of pain. It seems to have started with some routine wisdom teeth surgery. Or a period of intense stress in my life. I have no real answers about any of this, least of all about the beginning of it all.

What does this mean, practically speaking? What do you have? What did the doctor say? (Yes, I hear you speaking as I write). The doctors say nothing. Or they say many things, which is the equivalent of saying nothing in practical terms.

This thing I’m writing here, this is an attempt to carve out some meaning from my experience. I initially wanted to write something more abstract about the medical system, or about the aetiology of stomach pain, but what I’ve settled on is something a lot more personal. I’ve tried to capture what it’s like to be me at this precise moment in time. I have some conclusions and a sense of some pathways that have opened up ahead of me towards the end, but that’s all quite provisional.

A year or two ago I came across something called a keukegen. See the picture to the side. These are Japanese folkloric creatures. They are, in the words of one online source:

“particularly filthy monsters commonly found in populated areas. They are the size of a small dog, and appear simply as a mass of long, dirty hair. They make their homes in cool, damp, dark places, and are particularly fond of living under floorboards and around run-down homes, where stuffiness, moisture, and lack of human activity create the perfect breeding place for sickness.”

They are often cited as explanations for complicated illnesses that appear without a clear reason or pathway.


I grabbed on to the idea of externalising what I was feeling — or the cause of what I was feeling — into this shaggy creature. I loved too how this somehow allowed me to feel some kind of compassion for whatever was going on. The creature perhaps can seem a little sinister, but mostly it doesn’t seem like what you’d consider to be a scary depiction of illness or pain. There is somehow some kind of reassurance in the keukegen. It'll stick around as long as it needs; while it's here I might as well feed it and take care of it.

A lot of the experience of pain is a mental game. You get quite good at the somatic dialogue, listening to what the body has to say, sometimes reacting, sometimes choosing to just be there with it, sometimes trying to talk back. Dialogue is the ideal, you see, and not always achieved. Sometimes it's just the somatic lecture, with me trying to interpret the signals that my body has to communicate to me.

You want these signals to have meaning. You desperately want all of this to have some kind of meaning or deeper purpose. You need it not just to be empty sensation. In my more wise moments, or when I am able to step back, I realise or understand that there is no such thing as 'empty sensation'. Sensation is all there is. But at other times it feels like a disappointment.

You look to the past, casting glances at the wreckage of your life, all the things you haven't been able to do, everything you've had to turn down. You look to the future, always assessing the ways in which some decision will complicate your life in the future, the ways where you'll get something wrong or have to pay a price. These can be a bit like visiting a museum — glimpses of the lost life you'll never get to experience, everything encased in glass cases, all the plans you have to say no to, all the things you’re too scared to accept for fear of what the consequences may be.

You also lose your memory of a pain-free body. I sometimes try to imagine myself into that life, into a body where I did not feel these sensations, but it is like trying to visualise negative space. It feels like a logical impossibility.

Where to start? I have been in some degree of pain for much of the past three to five years. Memory of pain is notoriously (and, experientially) fickle, hence the huge variance in that estimate for how long this has been going on. I only started to really get serious about addressing the pain once it started to significantly affect my life and my ability to go about everyday tasks and my work.

To talk about pain is to enter a universe of metaphor and simile. There is nothing to put your hand on directly, and the measurement of pain itself is notoriously difficult to achieve in any kind of objective manner.

What does it mean for me and my day-to-day life? In the last 9 months I've often been confined to home, stuck lying in bed or on the sofa. Things that normally bring me pleasure became out of reach. They became impossible to do because I didn't have the energy, the mental space, the focus. I lost my creativity. My sense of possibility. My options. Simple things like planning out the coming month with travel for work became weighed down with what sometimes feel like astrological predictions. Nothing beyond the next hour or two seemed to exist with any certainty. I was forced to abandon any sense of the long-term future, existing instead in a tiny pod made up of the short-term.

A few months back ago, it began to seem as if things had taken a turn for the better. I had stopped taking medications for the pain. I was on a new treatment regimen. My body felt better. I started thinking that my body and my gut — and my ability to eat any kind of food — was more resilient. It's hard to convey how this felt in words — it was far more like a feeling of confidence than a particular thought or any objective measure of 'being better'. I felt like I could relax back into the experience of my life once again.

I started saying 'yes' more often. I started participating in more things outside the house. I started coming up with plans for work, for my personal and intellectual development. I started to think about travel in a timeframe looking six months ahead.

But the pain returned. I knew that feeling, the way it melded with my thoughts and my attitudes. What it did to my ability to plan, to think about the future, to move forward in my life. My vision closed down, it curtailed itself.

Instead of fanning out, opening to the world, I closed various doors open around me. I retreated to the few rooms that I knew well, and where I had some sense of control and familiarity. I adjusted my work schedule. I adjusted what passed through my mouth. I ramped up my self-care protocol, much-honed after months of trial in the trenches. This is a familiar place. I know what works — mostly — and what doesn't. I say no more often. I don't do things. I stay at home.

I put the walls back up around me. I closed myself off to experience, to the world. I returned to focusing more on what is happening right now instead of what will or might happen in the future, or in any kind of future that I want to construct for myself. This is a retreat. But it's ok, it's a retreat that is familiar, where I know what's going to happen, what kinds of pain and sensations are likely. I rest. I watch, wait and listen. What's happening in my body right now? Oh, that sensation. I know you. I've met you before. I know you.

Pain is notoriously hard to describe to those not experiencing it directly. There's an interesting history to the different attempts that have been made by medical professionals in an attempt to get a gauge of their patients’ pain levels, but the two more common methods are to make an estimate from one to ten (with ten being the most intense pain you've ever experienced in your life), or choosing between a series of smiling (or crying) faces on a piece of paper. As the subject experiencing pain, neither feels very satisfying or communicative.

The experience of pain in the moment is also quite different from the experience of pain as a long-term phenomenon. One is (mostly sensation) mixed in with some thoughts that are reactive in kind. The latter is mostly thoughts, or thoughts about thoughts — swiftly a recursive and enfolding phenomenon — where the moment-to-moment sensation falls to the background and a wider picture emerges.

Two useful words to add into the mix at this point: tolerance and threshold. Tolerance is the point at which pain becomes intolerable. Your threshold is the point at which pain breaks into your consciousness (possibly as contrasted to a kind of background feeling that's possible to ignore). I seem to have developed a high tolerance for pain over the past few years. I have grown to tolerate far more pain than other people would be able, especially moment to moment. My threshold shifts over time. I couldn't really say I have a fixed idea as to whether my threshold is high or not.

The more time you spend with pain, the more you realise how the usual metaphors start to break down. Pain is like a scale, yes; there is something that we can equate to more and less pain, but there are also degrees or different flavours of the same number on the scale. Spectrum is perhaps a better word — you can be more or less intense, but you can also be different colours on this intensity scale.

I often find that the different flavours of pain come with a colour or mood or shade association. The more time I've spent with pain — the hours really spent with the focus of my attention directed towards whatever sensations are inhabiting my body — the more I realise how many different gradations and flavours there are.

The smiley faces card method of grading your pain is more or less useless. For starters, the scale of the smiley pictures often doesn't make any sense. Why does the frown have to come before the grimace? Why is the wide-open mouth with tears the final position? It doesn't correspond to my pain scale, at any rate.

I tried to express a little of what my body feels sometimes in this drawing. It's not always like this — either the intensity or the precise flavour — but it gives you an idea. Like this piece, the drawing was just a snapshot in time. Pain never stays the same; it is always changing. This is one of the things I've learnt and that I find somehow reassuring; nothing is for ever after all. There is reassurance in that.

Most of my pain is felt or begins as a sensation in my abdomen. Following my own observations plus the investigations of a series of doctors, it seems that this is related to an imbalance of gut bacteria and some infections and weaknesses of that gut. Pain is sometimes caused by an excess buildup of gas in the gut — trapped there by who knows what — or sometimes just a phantom pain all of its own. Figuring out the precise pieces and tessellation of this cause-and-effect puzzle is frustratingly hard to do, and I gave up any hope of real answers a couple of years ago.

If it’s caused by something I ate, or if I’m experiencing some kind of flare that that moment, then I experience that as a sort of torture from the inside. The slow passage of food through my intestines is accompanied by an intense sharp pain, as if a ball wrapped in razor blades is attempting to pass through my digestive tract. Everything is inflamed, raw and highly sensitive to every single inch traversed.

That pain sometimes becomes a whole-body feeling. It'll often reach this point if I've been ignoring it — trying to push through whatever work or exertion I'm currently trying to do. The signal becomes amplified beyond the origin point (the abdomen) and booms out from throughout my body. It becomes unavoidable.

There are some second-order pains that I experience. After several hours of intense pain, I can sometimes feel a kind of tiredness or exhaustion. This is a kind of mental lack of energy. I sometimes get headaches. I sometimes find that the pain saps the energy that allow me to sustain or find my natural (or, at least, in the past it was natural / default position) default mood.

Sometimes the pain will be so strong that I have to lie down, curled up in a ball. This is my not-so-subtle invitation to spend some time with it. Sometimes I can ignore it a little but keep it in mind so that it doesn't become bigger. Sometimes it'll be directly related to what I just ate. Sometimes it appears out of nowhere. I fairly long ago abandoned the need always to find a reason for the pain's appearance each time.

Most of this is just telling stories, making up a narrative that may or may not relate to reality. And the thing with stories, I came to realise, is that they can change the pain as well. Sometimes for the better, often for the worse.

The pain is constantly changing. Never the same. There is almost always some level of pain on a day-to-day basis. There are periods of acute pain flares. This is when I need to cancel everything, give in to whatever experience my body wishes me to have. They can be predicted to a certain extent — certain things, were I to eat them, would certainly provoke such an acute episode — but sometimes come out of nowhere. This unpredictability is what makes it difficult to live or plan with any kind of medium-long term plans.

For the most part this pain I experience does not conjure up any kind of fear. These are pains I know. They are almost a kind of friendly presence by now. Old pain becomes part of the furniture. It is new pain, new sensations in new places or in new configurations, that can sometimes provoke fear. The more time that passes, the more I realise that these are all variations on a theme. They are all sensation, unpleasant sensation to be sure, albeit with something dysfunctional about the messages they send.

After a while, you start to get good at feeling the sensations in your body. Sometimes your body literally stops you in your tracks and you have to go lie down. Distraction makes things worse. You just have to be with the unpleasant thing that is happening. The pain, the uncomfortable sensations, the sense of powerlessness and the things you are unable to do. It’s useful to try not to overdo things on a particular day, or part of the day. You can push yourself, but then you won't have anything left over for the next day or for the evening. If you push yourself too hard, maybe you push yourself into pain. All the observation is a critical part of ensuring things stay manageable, within the limits of what is manageable and controllable.

You get to know certain sensations, or certain patterns of sensations. Some of them become familiar, and thus seem less threatening even if they are painful. You start to discount those sensations; they become more of the background. They become your new baseline. You aren't well, you don't feel well, you lack your full energy and aren't living as you fully could, but you just accept everything. You stop asking for help, stop going to doctors, stop considering the situation unacceptable. You accept it. Sometimes this is useful, other times not. I've found myself in that place at several points. Sometimes it's just a break, it's a space in between treatments, or its a place where you find yourself needing to pull back from engaging with the world, to pull back from hope — the hope that there is a straightforward medical answer, that the medical system can and will solve your problem.

The consequences of this ongoing pain experience are manifold and interact in complex ways. Frustration and grief are both good words to encompass these various responses.

To start with, a high tolerance for pain makes doctoring hard. After months of pain, you adopt to that pain as your new baseline. After doctors prove their ineffectiveness, you stop going to them because you know that the tools in their kit aren't able to address the root cause of what's going on.

The more the pain continues, the more I lose my trust in my own ability to interpret my own pain. In the beginning, pain seemed to mean something ("something is wrong! pay attention! fix me!”) but now after so many months of signal, of this alarm bell ringing, I have lost trust in the meaning it is trying to impart. It has become the new normal. I am more used to ignoring it, to being with it and not reacting to it, so it somehow fades into the shadows of normality.

Chronic pain is not just about the pain, as I stated above. It's also about the second-order effects, the loss of energy and of mental clarity. In periods of acute pain, or even just as a general pattern, I find that I am unable to go as fast as my mind wants me to go. I’m certainly not able to take on or handle the things that I recall being comfortable doing in the past, a few years earlier.

When I read in a book last year that fourteen percent of cases of chronic pain lead to suicide attempts, I could see and feel how that could be the case. I feel lucky that my pain ebbs and flows somewhat, but I’d be lying if I didn’t admit that the thought hadn’t passed through my mind at my worst moments.

Hospital visits mean lost work hours as well as a steady mounting influx of bills to pay.

The dietary restrictions that I've found myself adopting mean that eating out, or eating with anyone else, is more or less impossible. This narrows my social circle, already somewhat narrow to begin with. Spontaneous decisions to stay out in town, to get food as a takeaway or to attend things like conferences or work trips require intense planning and forethought. Everything needs planning and consideration ahead of time.

Then there's what it does to my mind: chronic pain can turn even the nicest person into a far shittier version of themselves.

The loss of control and freedom to choose my life's path and options is a frustration.

In periods of acute pain or when my energy is too low to participate in life in any kind of active manner, this is when I have the feeling that life is moving on around me. I am missing. I am still on this planet, joining everyone in this journey around the sun, but it is as if I am absent.

There is also an occasional anxiety and the desire to push the pain away. This is usually short-lived since it is not a useful way of relating to the pain, but it does occur and is not pleasant as a sensation.

There are some other consequences of the pain that are somehow less obvious.

I am more isolated and disconnected than ever. There is simply no way to convey the day-to-day experience — nor the energy or even the inclination — to anyone apart from a very small core circle of people. This means I can't really share the experience with anyone when I meet them or talk or interact with them, since to do so would require too much background explanation and context. So I just don't bring it up. You feel pretty alone pretty quickly when this is what's going on.

In the beginning, or in occasional moments where I've agreed to do something or other, you feel like you're getting a reputation for being flaky and cancelling appointments and or commitments. I recently had to go back through my calendar to find something from a few years back and I was struck by how many events, appointments and work commitments I'd had to cancel or pull out of at the last minute because my body wasn't up to it. Not only do other people find this inconvenient and wearing after a while, but you lose a sense in your own ability to stick to things and/or commitments after a while doing this.

Another consequence of being ill in any kind of not-so-easy-to-explain way is that you have to suffer through and tolerate other people's armchair diagnoses and well-intentioned-but-wearing interventions into your health. Everyone has an opinion. After a while you learn not to share things with people since you can't face explaining the whole story and then you can't face their explanations of what they think is going on, their presumptions to know your body better than you do, and their questions — as if you haven't already thought everything through a thousand times as to what might be going on.

If you don’t have a single-word medical diagnosis your pain is not taken seriously by others. If doctors haven’t found something that’s wrong, then that somehow means — though people rarely say this out loud — that there is nothing wrong with you. To have a chronic pain condition is to suffer through the shaming, doubting and negation of what you feel by others.

My interactions with the medical system have been instructive, if only in a negative sense. In the UK, where I began some of my investigations into this pain, most doctors simply don't have the time to listen to the whole story, to really delve into the details of what is going on. My general practitioner doesn't even take face-to-face appointments as the first point of call; you first get screened with a five-minute phone call. Then if your condition is deemed serious enough, you get an appointment to see the doctor which is limited to 10-15 minutes.

The body is a system. The medical structures as they currently exist doesn't treat that system, however. They treat individual parts of that system. It has developed a pretty good sense of acute conditions and things going wrong — if you get shot, stabbed, have a heart attack or a serious allergic reaction, you’re in good hands. These are all things that the medical system does pretty well at fixing. You’d do well to go to a doctor or a hospital to deal with those things.

What it is less good at is fixing or addressing systemic conditions that have multiple causes, or that are caused by complex interactions between different systems and groups of causes. Most kinds of chronic pain conditions — characterised as something ongoing and recurring for a lengthy period of time, sometimes even absent any clear or specific stimulus — are these kinds of complex problems.

I saw my GP, received referrals to various specialists. I was referred for followup tests. All the different parts to this universe of treatments were characterised by two- to four-month waiting lists. In between treatments there was no followup. The system wasn't configured to link all the parts together. Once one specialist ruled something out, I'd get sent back to square one with my GP.

Eventually, the default position for unexplained abdominal pain that reoccurs or exists on some kind of chronic time-scale is a diagnosis of 'irritable bowel syndrome'. As most doctors will willingly describe, this is a diagnosis of exclusion: they haven't been able to find anything that fits into a specific 'bucket' so you end up with 'this is something else but we don't have a word to describe it’. You'll usually receive a lecture on clean eating, perhaps something about gluten or FODMAPs, as well as instructions to try to 'manage stress'. Any further investigations are usually much harder to initiate at this point because the doctor — by putting you in the IBS bucket — has essentially decided that there's nothing left to investigate. At this point you're on your own.

If you have an uncharitable doctor, or if you discuss it with (mostly well-intentioned) family or friends) you'll hear about how it could 'all be in your head'. You'll hear a lot about stress, and how you should 'really try to get a handle on that'. Your doctors will tell you to 'learn to live with it’ (read: ‘we don't know what's going on so we're giving up searching any further’).

When you go see a new doctor, particularly after a few years of a chronic condition, you have to play a delicate balancing act in terms of the quantity and type of information you reveal about your story. Tell too little and the doctor won't understand what's going on and you won't get any kind of solution. Tell too much and your doctor will quickly put you into a hypochondriac bracket in their minds.

Sometimes I'll be in a lot of pain and I'll know — in an acute episode, for example — that this kind of pain will probably dissipate in a day or two but that I need something to get through it for right now. I've tried enough of the pain medications out there by now to know which ones are good for which manifestations of acute intense pain. The problem is that if you go in requesting a certain kind of pain medication — particularly anything of any kind of strength, and especially if it is any kind of opiate — you'll be labelled 'drug-seeking' and you may never get what you came in for.

For non-acute episodes, doctors will ask you to rate the pain on the 1-10 scale. Because of my high tolerance, my instinct is to rate the pain fairly low because it is all — on some level — tolerable (quote unquote). (Just unpick that word ’tolerable’ for a second in your mind). Or even if it is quite intense, I've lived with it long enough that it doesn't necessarily manifest on my face or my body as if there is any kind of intense pain. Just because I'm not crying out, wincing or bent over doesn't mean that there is no pain. In fact, in my worst moments of pain I'm simply unable to get to a doctor or hospital and you'll find me instead in bed or lying on a cool floor waiting for it to pass.

Abby Norman’s fantastic book Ask Me About My Uterus has this section on how you can grow to some kind of uneasy familiarity with pain:

“Bodily agonies that do not end beget a kind of forced intimacy with pain that, not unlike other intense relationships, can eventually bleed into something tedious and almost unremarkable in its enduring presence. Its place in our lives can become ordinary and even, at times, oddly reassuring. The moment that pain owns us is not when it chokes our breath, when it knocks us down, or when it steals our pleasure. Pain becomes our master when we wake up one day and realize we no longer fear it. When we come to regard it as not something separate from us, but something of us. As much as we have labored to resist this in our minds, our bodies acquiesce. Our hearts beat, our cells divide, our nerves—frayed though they may be—fire, and one day we realize that we no longer remember what it feels like to live without pain. What becomes remarkable is not our body’s distress call, but the silence. Really, it’s the silence that we fear, because it does not mean we have been healed. Silence after pain usually marks our body’s inability, or unwillingness, to adapt again, to heal itself, and to persist as we do for an answer, or a reason, for our suffering.”

There is also a kind of shame in this familiarity. The dominant narratives that you’ll hear around illness and healing usually have some kind of ‘struggle to beat adversity / struggle to win’ theme to them. Coming to a familiarity, making peace with pain, or surrender of any kind is somehow socially anathema. That may be the case, but I have been finding something compelling in the feeling of reassurance.

I gave this piece a slightly odd subtitle. ‘A love story’. Amidst all the uncertainty and inability to describe (or understand) what’s going on inside my body, I have grown much closer to all the myriad sensations and energies happening from moment to moment.

The experience — an extended period of illness and suffering in general, chronic pain in specific — has taught me a lot along the way. I’m far less disconnected from the everyday somatic experience of my body than I’ve maybe ever been in my life. I’ve learned all sorts of things about stress, trauma, the mind-body connection as well as ways of coming to terms with it all. I’ve learned that the treatment of chronic conditions by the normal healthcare system is truly broken. I’ve learned that placebos are a real and sometimes beautiful thing.

I’ve been continually surprised at the body and mind’s ability to adapt to a new normal. Shifting baselines are both a blessing and a curse, but the way I’m constantly calibrating and coping in response to changing circumstances is a marvel to observe.

Amidst this wreckage of what I once thought ‘normal’, there are things that help from time to time. Protective and defensive measures seem to work the best. Awareness and mindfulness help prevent small irks and aches from growing when I try to ‘just push through’. Following a restricted dietary regimen can sometimes help, but not when I’m so far gone that my body reacts even to the good stuff. Stress and time management is almost a truism, but it’s achieved that status for a reason. Sleep is possibly at the top of my list of things that make me feel better; it’s also the first thing I’ll start neglecting the moment I start to feel better. Slow kinds of movement, be it walking or yoga, have been useful in reconnecting me to some kind of energy and reminding me that there is some life or presence in me yet. Acceptance and a reminder about death (not getting too attached to my body and the world) is a surprisingly handy mental model to have when going through the worst moments; in the end, everything passes.

When pain shows up all guns blazing, that’s who’s in control. For someone who generally has a sense of how they’d like things to unfold, this powerlessness took a long time to come to terms with. But there’s some sort of relief in the surrender, even if that’s also somehow layered alongside shame. And since we’re quite far down the road of dealing in metaphor and story by now, maybe it’s just a question of taking care of this scraggly keukegen beast for as long as it takes. One day perhaps I’ll wake up and it’ll have decided to move on to take up residence in someone else’s back yard.

Pain is a profound teacher. If only the experience weren’t so unreasonably unpleasant.

Python Virtual Environments, Testing Environments and Markdown Strikethrough

I spent part of this afternoon fixing things in my PDF splitter code.

  • I learnt about virtual environments and the various choices available in Python. This was the most useful overview. I ended up choosing pipenv which is also outlined here. It installs a Pipfile in your directory which is an equivalent to the old requirements.txt that was previously used. This means that whenever you use pip to install a new package, it’ll remember and update the file accordingly.
  • For testing, I ended up holding off for the moment. It wasn’t immediately apparent which of the various testing suites I should be using and the examples given in places like this used strange syntax. I’ll have to tackle this later, but for now I’m putting it on hold.
  • I learnt that you can make some text strikethrough (EXAMPLE) in Markdown by enclosing the text in two tildes (~~).
  • I read about application layouts / structures and made some initial decisions about what files to include in my project. Some of this is overkill for where I am currently, but soon enough this project will expand and I’ll need a standard structure format.

Tomorrow I want to start working on my regex search-and-rename function. I’ll start by figuring out the right regex string to use for my search, then I’ll figure out how to add in into my script.

Table Tests in Go

ScreenShot 2018-06-18 at 21.47.05.png

Today I wanted to stretch my use of test scenarios with Go. The example I described a couple of days ago basically had me running individual tests for specific values. What I wanted was a way to test a bunch of different values for the same function. Enter: table tests.

You can see the code I ended up with partly in the image above but also on Github here. It took a while to get there.

I started with some notes I’d taken during Todd McLeod’s excellent GreaterCommons Go course. Those notes were enough to get a framework up and running. I understood the principle: you create a struct to store all the different values, loop over them all to check whether the test fails in any particular scenario.

When I ran go fmt at the end to format my code, it gave me an error as it refused to build:

I could see that it wanted two ints and I was giving it a slice of ints. Basically this turned into a hunt for fixing my loop and which values I was spitting out at various iterations of the loop.

I ended up isolating the part of the code that was causing the problems, putting it up on the Go Playground so as to isolate exactly what was going wrong. Once I’d figured out exactly how to handle the loop, I could then bring that logic back into my main_test.go file.

Now I know how implement table tests in Go. My next exploration will be around functions that aren’t located in the same file. So far I’ve been mainly using the same main.go file for all the code I’ve written, but a step up in the complexity will be to interact with different files.