Fasting Without Fasting

Fasting is a fantastic way to treat type 2 diabetes. With no food to digest, your insulin levels will drop, and you’ll burn through fat in your liver and the rest of your body. And if you fast for multiple days your body will see additional benefits, such as autophagy kicking in and recycling old cells.

But fasting can be challenging! The ritual of multiple daily meals is deeply embedded into our lives. And, of course, the actual hunger is is kind of annoying to deal with (though it isn’t as bad as you might imagine).

I’ve experimented with an alternative called a fasting mimicking diet (hereafter referred to as an FMD). L-Nutra sells these as a kit under the Prolon brand and that’s what I’ve been using so far. The biggest drawback is that it’s fairly expensive at $250 (and that’s doubly disappointing when you factor in what a low calorie diet this is supposed to be!).

This isn’t quackery, either (despite an endorsement from Gwyneth Paltrow). It’s backed by decades of research on longevity performed by Dr. Valter Longo and his team. He devised this FMD protocol for cancer patients about to undergo chemo to give them better results but his research has shown that periodically going through an FMD will improve longevity and other important health markers, and the positive effects of the FMD continue even after you resume your normal diet.

Is the FMD easy to do? I don’t want to blow smoke up your ass. It’s not a walk in the park, but I’ve also done a 5 day water fast before, and the FMD is way easier to do, and it’s easier to incorporate into your daily life.

The kit comes in a box roughly the size of a shoe box:

prolon kit box

(imagine the first three boxes are in there too)

When you look at it, you think “hey, this isn’t so bad.” Of course, then when you grab one of the boxes and remind yourself that this is all you’re eating today, it’s a little more daunting.

prolon day 2

The food consists of powdered soups, kale crackers, olives, and snack bars. They also include some supplements, some teas, and for days 2–5, a glycerin-based energy drink.

This is how you can expect your week to go:

  • Day 1: “Hey, this isn’t so bad! I get 2 of these nut and honey bars, two soups, a package of kale crackers, a chocolate bar type thing, and some olives. It’s actually pretty filling!
  • Day 2: “Hey, wait a minute, this is… less food than yesterday. What happened to my kale crackers and my second nut bar?
  • Day 3: “Okay, we got the kale crackers back but what the hell happened to my olives?”
  • Day 4: “Oooh, I’m almost done! Good thing, too; this is starting to get a little bit repetitive.”
  • Day 5: “Well I’ll be damned, I did it!”

I made slight modifications. I largely didn’t bother with the glycerin drink on days 2–5; It struck me as empty calories (it’s basically water sweetened with glycerin with flavor added). To compensate for the calories the drink would have had, I augmented some of the meals with celery and ate some extra olives (I’ve kind of developed a taste for them!). One afternoon I had some seaweed snacks, and on the final day I augmented the final dinner with some slices of heirloom tomato. I was careful to not go over my overall calorie intake, and I have no regrets about any of these modifications. Especially the heirloom tomato; is there anything better than a nice ripe heirloom tomato?

Being a diabetic, I was skeptical about how healthy this FMD would actually be given that almost half the calories are from carbs. And while that’s a high percentage, when you’re eating <800 calories a day, the carbs aren’t really enough to do much to you (even when some of the soups use rice or potato flour as their first ingredient, both foods considered to have a high GI). And after a couple of days, you see a precipitous drop in blood sugars.

The morning I started my most recent FMD my glucose at 9am was 139. The morning after day 5, it was 119. More importantly, my ranges of blood sugars changed dramatically. On Day 1 of the FMD, they ranged from 109–243. The day after I finished the FMD, they ranged from 98–177. Today so far (2 days after the FMD ended) they’re ranging from 106–133.

glucose ranges spanning several days showing a dramatic improvement in glucose after the FMD

That’s pretty damn good. And during the FMD I wasn’t even taking any diabetes medicine (I’m taking them again now, and that probably explains why my levels today look even lower)

When I first did an FMD I was incredibly skeptical of how well it would work compared to fasting; your caloric intake is almost half carbohydrates, after all, and the primary ingredient in some of these soups is potato flour and rice flour, which struck me as not particularly healthy. But keep in mind that while the percentage of carbs is high, the absolute carb count is very low. And lo and behold, my blood sugar numbers started looking quite good after a couple days into the FMD, and importantly, even after you’re done with the FMD, your insulin response is improved and blood sugar numbers stay quite good.

Also, I lost at least 5 pounds during the FMD (I say “at least” because I was afraid to weigh myself at the beginning, so my baseline is from a day between my last FMD and the morning after I finished this FMD).

My plan is to start doing an FMD every couple of weeks. For my next one I’m going to use foods I make myself, just to save money and offer myself a somewhat improved variety of foods. I feel super optimistic about this approach, too; each FMD is not a huge commitment, and I just have to spend the bulk of my willpower budget in short five-day increments.

Uncategorized

Walk the Planck

If you know me you know my collection of clicky keyboards has been steadily growing since I bought my first one in April of 2012 (a Das Keyboard, if you were wondering). In recent years, though, I’ve developed an affinity for a specific subgenre of keyboards: keyboards that are 40–50% the keys of a full-sized keyboard that are ortholinear. One of the most popular of these keyboards is the Planck, an absolutely adorable little grid keyboard with a 4×12 arrangement of keys.

When I’m recommending a mechanical keyboard for a friend who is relatively new to the game, I don’t want to throw someone into the deep end with a keyboard that also comes with such a dramatic learning curve; typically I aim to provide a soft landing in the mechanical keyboard world with a pretty standard looking full-size or tenkeyless keyboard that is laid out pretty much like a keyboard your computer might come with. That way, I give them a fair shake at getting to love the much better feel of the mechanical key switches without a ton of frustration at having to re-learn how to type.

But lately I’ve been inclined to push people more toward something like the Planck as their first clicky keyboard.

Just look at it:

planck

It’s cute! It’s just 47 or 48 keys (depending on whether you opt for a double-wide spacebar). That’s super approachable, especially compared to something like the Ergodox, which is full of these clusters of keys of different sizes:

source: ergodox EZ

When you first lay your hands on a Planck you’re going to quickly feel like you have a grip on the keyboard; in the top three rows every single key is can be reached by moving a finger no more than one position from home row. And instead of being overwhelmed, you’re actually likely to be asking “Hey, where are all the keys? Don’t I need more?”

And you don’t! The Planck’s clever firmware makes fantastic use of limited keys by making each key do more. Modifier keys like Shift and CTRL can be dual-purpose; for instance, when I tap my CTRL key quickly, it’s treated as an Escape key, but when I hold it, it’s a Ctrl key.

And, of course, there are the layers. So, while you’ll notice there is now row of number keys, they’re actually right there, in the top row, on a different layer. You hold the key to the right of the spacebar to access this layer:

Layout of planck layer

When you factor in how easy it is to reach each key, you’ll find it actually feels quicker pressing 2 keys to press a number than it would have felt to reach up 2 rows to get to that number row. And because the keys are in a perfect grid, your fingers will love how easy and unambiguous it is which key is which! How often do you hesitate for a split second while you try to guess by feel whether you’re hitting the 2 or the 3 key in a staggered layout? With a grid, it’s never in question!

Your Planck will typically come pre-configured with a standard layout that works quite nicely, but you aren’t forced to live with that. The Planck is a fully programmable keyboard. That means its layout can be changed at the firmware level (which also means you don’t need to install special software or hacks on your computer to customize your keyboard’s layout, and you can plug your keyboard into any computer and it works just as you expect). This is my base layer’s layout (I’m a sucker for arrow keys in an inverted-T layout):

My Planck's base layer layout

The Learning Curve

My first keyboard in this category was a Preonic, which is like a Planck but with an extra row of number keys on top. I thought the extra row would make for a smoother transition, but eventually I realized the layers were plenty powerful and the extra row was an unnecessary crutch, and I rarely am using my Preonic anymore.

As a programmer, I’ve found that if I try to dive face first into a new type of keyboard at work, I will get frustrated really quickly. Instead, I spend time becoming proficient in more conversational typing first. I’ll type text conversations with people on it, or write up some blog posts with mostly prose and not a ton of special characters. Then, when I become proficient, I’ll try to gradually introduce more typing that involves the other characters.

If you choose a Planck EZ, they offer a graphical online layout configurator that also has a training mode, allowing you to see your layout in real time as you are holding different layer keys. I haven’t tried this yet myself (it was added after I was already pretty good with the keyboard) but I really like the idea of this.

And speaking of layout configuration, as you are learning the keyboard’s layout, I encourage you to make layout changes early and often! If you keep mistaking one key for a different one, why not just change the layout so that it matches your expectations? Are you finding that you keep hitting the Enter key in inopportune situations? Move it somewhere else or put it behind a layer to avoid accidentally sending a message prematurely!

Customizing

If you haven’t already gotten the hint, Plancks love being customized! After all, the whole keyboard design is open-source from the start, so it was made to be tinkered with; it’s not a black box you’re expected to enjoy as-is. Two popular Planck versions (Drop.com’s and the Planck EZ) have circuit boards where you don’t have to solder the key switches on, meaning you can try out different kinds of key switches to your heart’s content.

Since it’s such a small keyboard, you only have to buy 48 switches to have a full keyboard’s worth, making it cheap to try new kinds out! For the same reason, Plancks also make a great kit (the drop.com version is a kit, for instance). Even if you buy a version that needs soldering, soldering a Planck together is not nearly the undertaking that a full-sized keyboard is).

And, of course, you get to enter the world of customizable key caps! Most custom keycap sets offer a variant to make them compatible with the Planck (look for the “ortho” key set). For the most part it’s not too hard to just take some existing key caps from an existing keyboard and put them on your Planck, but for the bottom row you’ll have to get a little creative since most standard keyboards’ bottom rows don’t have 11–12 single width key caps.

A keyboard that is truly yours

Philosophically the Planck warms my heart. The Planck is a community-designed keyboard, and it is open to its core. When you buy one, you aren’t buying from a big, faceless corporation; you are buying from a cottage industry of small keyboard makers. Hell, you don’t even have to buy one from someone else if you don’t want to; you could build one yourself by hand and hand wire it if you wanted.

The keyboard will give you years of service, but it’s also a simple enough product that it is highly repairable. If an individual key switch stops working, you can replace just that switch. If a component on the circuit board fails, you could replace just that, or have a friend with some know-how replace it. It’s a refreshing departure from so many of today’s electronics.

And most importantly, you aren’t stuck choosing an inferior product just to get something built with these values; the Planck is objectively a better keyboard because of its openness, not in spite of it.

A keyboard for all

The Planck’s birth may have been among some passionate keyboard enthusiasts, but I firmly believe that it’s a keyboard suitable for the mass market. As friendly as the keyboard is to being customized and endlessly tinkered with, it’ll serve you just as well if you set it up just the way you like it and never change anything again.

The keyboard is a very intimate part of the computer. It is the most tactile part of it, and it’s the part of the computer you use when you want to precisely express your thoughts. It’s a peripheral that’s essential to people who work at a computer for a living, and if you’re like most computer users you’re just using the one that came with your computer without giving it a second thought. Believe me, it’s worth exploring better options, and a great keyboard is a solid quality of life improvement!

The Dunning-Krueger Years

I’ll periodically get these flashbacks to moments in my career where I can now realize that I was way out of my element and didn’t know what the fuck I was doing. Having worked at an early stage startup I ended up in a role where I was managing other engineers and I was not yet experienced enough to realize just how unqualified I was.

On one of these occasions, one of the engineers on my team was struggling to get some work done in time for an upcoming deadline.

And since I was presumably this clever and brilliant manager I figured I’d be able to swoop in, work my magic, and get this engineer back on track. There was a company-wide outing coming up that week, and I told him “hey, let’s both stay back at the office and we’ll knock out these issues together.” For me, this was perfect because I considered the event to be a waste of time anyway and I also got to be the down to earth, hands-on manager who rolls up his sleeves and gets shit done.

So we stayed behind to hold down the fort while the rest of the company went to this fun outing. In practice, I was of little use to him because I wasn’t intimately familiar with the codebase he was working on, and despite him working primarily in JS, he was perfectly proficient in Ruby and didn’t really have any need for 26 year old me’s sage advice as an expert Rubyist of… probably a couple of years at the time.

So I mostly spent the afternoon dicking around on the internet, not really helping with much, and I guess he got to chip away at his issues for an extra afternoon, and an extra afternoon wasn’t make or break. In retrospect, this was mostly a dick move. Instead of singling this lone engineer out and keeping him from a bonding activity with peers, I should have been monitoring the project more closely so that I could have directed some help his way weeks prior, when it would have mattered. And I would have been a much more down to earth manager had I been a good sport and attended this outing.

This engineer’s life has since then taken a dramatic turn; he eventually left tech entirely and according to his Facebook profile he teaches yoga and practices healing through sound baths and meditation. And to be honest, having worked in tech now for a little while, that does sound like it would be a refreshing and fulfilling departure from the shenanigans people like past me subjected people to.

I’m glad that I’ve grown enough that I can look at my past self and facepalm so hard. I’m not proud of whatever collateral damage I’ve left in the path I took to get here, and I hope I still have enough growth ahead of me that I can look back at even this post and think “wow, I was insufferable.”

Loving America

Awhile back I was thinking a little bit about the idea of loving my country as I keep learning more about history and learning how pervasive some of America’s problems are.

I had a sort of lightbulb moment that might not be out of place in a Sorkin TV show: there are two different ways you can see America. You can see the America that was home to slavery for centuries, the America that only let rich white male landowners vote, the America that refused to allow gay people to marry. Or, you can see the America that was able to overcome each of these things.

But that isn’t enough anymore for me.

From an economic perspective, America’s been awfully good to me. I have been able to live a life where my success has been correlated with the effort I put in over the years. There are a lot of other countries where these same skills and work wouldn’t have gotten me nearly as far as it has here, and I don’t think there’s anywhere else I could have been born and had a greater outcome than here in the US. I think a lot of people feel that, and that gives them a lot of national pride.

But for every one of me in America, there are several people who don’t get that same level of opportunity. America doesn’t do enough for those people.

America is full of deep issues. There is serious inequality everywhere you look, and not just economic inequality. There is inequality in people’s access to democracy itself with long time systems like the electoral college and the fact that the Senate gives some voters substantially more representation than others. Hell, we have entire subgroups of our population that are terrorized by law enforcement.

America isn’t great just because a good sized chunk of people have been able to be relatively well off. America’s impressive accomplishments alone can’t keep making up for the serious ways we are falling short.

So I don’t think my love for America is unequivocal anymore. Rather, my love for America now extends as far as America is able to continue being that country that evolves to live up to the ideals of meaningfully offering liberty and justice for all.

I refuse to let anyone insist that anything less than that is the best I should be able to hope for, and you shouldn’t either.

Uncategorized

WWDC 2020: form vs function

I have seen a handful of these takes about WWDC and while I appreciate what they’re saying, something rubs me the wrong way about it.

We all miss getting together with friends and meeting people, but this overall “I get that the content is better, but networking!” sentiment some developers have shows that they value their own nostalgia and enjoyment of networking over better WWDC sessions and accessibility for the wider community.

WWDC’s primary purpose isn’t for you to make new friends. Its purpose is to help inform developers of new Apple technologies.

This year tens of thousands of developers got to have a much better WWDC with better, tighter content because of this new remote format. WWDC videos often contain the best information about new technologies and serve as a valuable reference for years. Often times the best way to learn about a particular technology is to go back and watch the WWDC session where it was first introduced, and for everything that was introduced this year, we have fantastic materials.

And although networking and seeing friends at WWDC in person is fun, attending in person is a privilege. Only a small percentage of developers have the substantial funds (and depending on what country you’re from, the ability to safely travel into the US without hassle from customs), and are lucky enough to win the lottery for a ticket.

WWDC in person is great for the people who get to go. But every year as the developer community grows that becomes a smaller percentage of the community. If being in person with others at WWDC brings new friendships and opportunities to the attendees, then it just means that attending WWDC amplifies your privilege, and we need to acknowledge the inequality that leads to.

Ideally, I hope next year’s WWDC format doesn’t completely abandon the perks and better video production values we got in 2020. We would have a live keynote and SOTU for Monday, and prerecorded sessions would be released throughout the week. Instead of presenting live sessions, Apple engineers could instead give more labs and in-person assistance during WWDC week, Apple engineers could be offering sessions with individual developers remotely throughout the rest of the year. That would make for a better WWDC for everyone.

Or maybe Apple will want to stick with a WWDC where everything is pre-recorded and remote (that’s probably a lot less stressful for them!) and instead of there being a single Apple developer conference that’s massive and expensive, smaller, local conferences can sprout up around the world for people to enjoy each other’s company and talk shop. It wouldn’t be quite the same as what WWDC was before, but then again, Apple’s developer community is a lot bigger, diverse, and spread out than it was before, and it’s time for WWDC to adapt to that new world.

Uncategorized

Live-ish glucose data on Apple Watch

Since I was diagnosed with diabetes a few years ago, one of my best coping mechanisms has been to lean into it by using it as an excuse to play around with gadgets to track it.

And lest you think that’s a waste of time, it’s really effective! There is a direct relationship between how well controlled my diabetes is and how much I’m tinkering around with this stuff.

One of the most powerful tools in my diabetes management arsenal is a system called the FreeStyle Libre. Instead of having to prick my finger every time I want to check my blood sugar, I instead will insert a sensor onto my arm every two weeks, and whenever I want to check my blood sugar I can scan the sensor by swiping my reader next to it. Or if I don’t have my reader with me, the sensor uses NFC so my iPhone can scan it too.

When I scan the sensor, I instantly get my current blood sugar level, plus 8 hours of past blood sugar data.

glucose data from LibreLink app

But the LibreLink app sucks. It isn’t a particularly good iOS citizen; instead, it feels like it’s just trying to mimic the reader’s own interface. And despite having this treasure trove of data, it won’t sync to HealthKit. You have to use a proprietary app called LibreView (although through a series of steps I can export the data and eventually get it into the Health app).

Basically, there are two extra features I wanted for my Libre sensor:

  • ability to see current glucose level by glancing at a complication on my watch
  • having glucose levels automatically synced to the Health app

Solution

Because the Libre sensor is NFC based, I would need something extra if I wanted to actually push data from the sensor to my iPhone/Watch.

And there does exist such a device called the MiaoMiao. It piggybacks on top of your Libre sensor and connects to your phone via Bluetooth, scanning the sensor every five minutes via NFC and pushing the data over to your phone.

There are multiple apps that work with MiaoMiao, and on iOS you can use either Spike or Tomato. After unsuccessfully trying to get the Spike app set up and realizing it was kind of a lousy iOS app, I opted to try Tomato, which is at least in the App Store.

The Tomato app works, but it is kind of a low-quality Chinese made app with the trappings you might expect from such an app–poor translations, a UI that lacks care, mandatory login with your Google, Facebook or WeChat account (Sign in with Apple was strangely absent despite supposedly being mandatory via App Store policy) and Watch complications that either truncate your data, or make really poor use of space.

apple watch face with blood glucose complications

However, the app does sync with HealthKit, if you have a premium subscription (interestingly, it doesn’t use Apple’s in-app purchase mechanism either; they prompt you for PayPal. I have no idea how Apple approved that as that is a blatant violation of App Store policy and usually the kind of thing Apple watches like a hawk).

So instead of using Tomato’s own watch complication, I am instead using HealthFace to set up a complication for my watch that displays the most recent blood glucose value.

This works beautifully!

apple watch face with HealthFace app complication

Ideally I’d like the HealthFace app to be able to display a chart of the last few hours of values so I have some sense of my glucose trend, but now that I have the watch complication I am watching its value often enough that I have a mental idea of how it looks anyway.

Miscellany

Some random facts that I wondered that aren’t answered elsewhere:

  • If you’re in the US it will take forever for the MiaoMiao to ship from China. I ordered it in February and it didn’t finally arrive until late June, although they lost the first one and had to ship me a second one.
  • If your MiaoMiao arrives and your sensor is already activated, the MiaoMiao can still connect to it. You don’t have to wait for a fresh sensor.
  • You can still pair your Libre sensor with both the reader and your phone while still using the MiaoMiao
  • The MiaoMiao sensor’s stickers aren’t that great at staying attached. I had to use some medical tape to tape the sensor down to my arm, but since then it’s stayed put.

Parting thoughts

As appreciative as I am that all these parts can work together like Lego pieces to give me a working solution, I’m still a little frustrated that Abbott doesn’t provide a decent end-to-end solution.

In Europe there is a new version of FreeStyle Libre with sensors that are Bluetooth-enabled, but the sensor only uses Bluetooth to alert you of highs or lows, and doesn’t push the actual glucose data to your reader, so that’s still a dead end.

But at some level this neglect is a blessing. Abbott’s not offering anything like a full SDK or anything for its sensors, but they’re straightforward enough to reverse engineer that we can at least cobble together our own solutions.

Uncategorized

A new WWDC

Speaking as someone who’s never attended a WWDC in person, today’s sessions felt like an overall improvement over an in-person event. Presentations felt tighter and more polished overall. It was probably a little less nerve-wracking for the speakers to have everything recorded ahead of time, even if they miss out on some of the live audience feedback and applause.

I realize that for the people who have attended WWDC in person this is for sure a downgrade for a lot of reasons, but for the tens of thousands more developers who get to experience the conference this time as first class citizens, this is an overall upgrade.

WWDCs for the past… decade or so have felt stagnant in their format that dates back to Steve Jobs. This year’s WWDC feels like Apple is finally breaking free of that legacy and trying something new that is true to the reality of Apple’s scale today. This year’s WWDC format also feels more true to the nature of working as a developer, something Apple hinted to in the outro video for the Platforms State of the Union, showing developers working in a variety of settings, sometimes late at night, sometimes with children around. By embracing a distributed and more asynchronous conference format, you are making WWDC feel like it’s for everyone, not just a privileged relative few who can make the journey.

Apple didn’t want to do this year’s WWDC like this; they were forced to do the event like this because of COVID-19, and I’m sure they’re eager to do live events again when it’s safe. And that’s great! I can’t imagine it gets much better than working hard on something great for people and hearing that thunderous applause when it’s introduced on stage. But the community has changed, and the defaults should change too.

It’s Time to Allow Sideloading iOS Apps

Apple’s firm rejection of letting Hey’s iOS app in the App Store is just the latest in over a decade of controversy over the rules and restrictions Apple puts on App Store apps.

I’m sick of having to keep calling on Apple to reverse some stupid App Store policy decision every several months. Let’s eliminate the problem at its core and stop requiring iOS apps to be distributed on the App Store.

We don’t need the App Store to be exclusive for iOS to be a safe platform. iOS’s security model is great, and sideloaded apps can be made safe by adopting notarization as Apple has for macOS. No one realistically thinks the human app review process is meaningfully making apps safer.

And this would be great for Apple; it frees them up to run the App Store however they want to because developers always have an alternative if they run afoul of App Store policies.

Maybe Apple feels pressure from investors to keep the services revenue gravy train running, but there’s no reason to believe that allowing sideloading is going to slow that down. The App Store will keep growing without exclusivity, just as the Mac App Store has. The App Store wins by being the most convenient way for customers to buy things from developers, and non-power users will always trust Apple to curate an App Store full of apps they know they will trust.

The iOS platform is a massive market, and Apple hasn’t been a good steward of its primary distribution channel. If Apple wants the truckloads of money that come with making the most profitable mobile platform, it needs to accept that it can’t keep running it with monopolistic, rent-seeking behavior.

Uncategorized

Tech’s lip service to racial injustice

As protests of police violence continue in the US we’re beginning to see the steady trickle of large tech companies posting to social media about the events in solidarity.

These companies only started putting out statements after massive civil unrest started to form. George Floyd was killed May 25. The next day footage of his killing became widespread, but it wasn’t until days later, when there was massive protesting in the streets, that companies began putting out statements expressing empathy.

And as kind as these gestures appear, they don’t make up for the fact that these same companies are more than happy to participate in being racist in the first place. Companies will happily pay lip service to a less racist world, but if it meant having to turn a way a customer that embodies institutional racism (like ICE, for instance), that company will just throw up its arms and insist that it’s their duty to sell to these customers.

When employees try to object to this behavior, the companies’ executives will dismiss these employees’ viewpoints as a “difference of opinion” and that they can’t just use opinion like that as a basis for doing business with a customer.

A difference of opinion.

As in, “it’s my opinion that we shouldn’t do business with an organization that is rounding up people and putting them in literal concentration camps.” You know, just a little difference of opinion!

Law enforcement agencies around the US have deep-seated cultural issues of institutionalized racism. It’s baked into the behaviors of police officers and misconduct is incredibly widespread. Law enforcement is able to carry out its misconduct because it has the help of thousands of vendors that sell them the things they rely on, from cars, to uniforms, to computers, to software.

Every tool and service that a police department uses is made by a vendor, and every vendor has a choice not to offer their products and services to police departments if they don’t believe the police departments are behaving with good conduct.

But none do.

I’ve yet to see a single tech company come out and say “we’re going to audit our relationships with law enforcement agencies and we will end our relationship with agencies that don’t meet our standards”. Shopify’s CEO shared a heartfelt comment expressing his disgust with the injustice of George Floyd’s killing, but apparently he felt that cutting ties with Breitbart would be too much of an injustice to them (he since deleted his original post on Medium).

It’s nice and cheap to put out a statement denouncing racism and companies are happy to do it. But ask a company to take a meaningful step to stop racism and they’re all too eager to shy away from it.

To tech companies, systemic racism is a PR problem to be managed as long as it’s easy to do so, not an opportunity to acknowledge their own substantial role in it.

Uncategorized
|  

Default values for hashes in Ruby

I was recently working on some code that involved hashes of arrays. As I was reading through some behaviors of Hash in the Ruby docs, I was delighted to see that you could pass an object to Hash.new and it would be the default value returned when you tried accessing a key in a hash that didn’t exist.

So, let’s try this out a little bit!

2.1.1 :002 > arrays[:colors] << :blue
 => [:blue] 
2.1.1 :003 > arrays[:colors] << :red
 => [:blue, :red] 
2.1.1 :004 > arrays[:colors]
 => [:blue, :red] 

Looks like it’s working! Let’s use another key.

2.1.1 :005 > arrays[:shapes] << :quadrilateral
 => [:blue, :red, :quadrilateral] 

Wait, whaaaa? Let’s see how my :colors array is doing:

2.1.1 :006 > arrays[:colors]
 => [:blue, :red, :quadrilateral] 

Oh, no! What is going on with this hash?

2.1.1 :007 > arrays
 => {} 

Okay, let’s read those Ruby docs more closely:

new → new_hash
new(obj) → new_hash
new {|hash, key| block } → new_hash

Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn't correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required.

There are two subtle things at play here. First off, giving hashes a default value doesn’t mean that anything is stored in the hash when you try to access a nonexistent key. That explains why my arrays hash is still empty even after I’m shoveling things onto arrays. This is sensible default behavior; a hash could grow without bound if by default a new value got added to a hash whenever it was accessed by a nonexistent key.

The second subtlety here is a reminder that in Ruby, objects are mutable. We are providing the hash a single object instance (in this case, a new empty array) that is returned as the default value when you try to access a key in the hash that doesn’t exist. If I change that array by appending things to it, I’ll still get back that same array object in the future when I access the hash by a nonexistent key.

I want the hash to work so that when I access a nonexistent key, I get back a new empty array, and that array is added to the hash. We can do this by passing a block to Hash.new:

2.1.1 :008 > groups = Hash.new {|hash, key| hash[key] = []}
 => {} 
2.1.1 :009 > groups[:colors] << :red
 => [:red] 
2.1.1 :010 > groups[:colors] << :blue
 => [:red, :blue] 
2.1.1 :011 > groups[:shapes] << :octagon
 => [:octagon] 
2.1.1 :012 > groups
 => {:colors=>[:red, :blue], :shapes=>[:octagon]} 

I’ve been using Ruby for years and I lost at least an hour recently because I wasn’t accounting for this subtle behavior.

Uncategorized