Always Learning

I met up with some of the people from my new Launch Academy cohort, and in the midst of answering one of their questions I discovered an erroneous assumption that I had been making.

When I first encountered a structure like a Javascript JSON literal or Ruby hash, it was the Python dictionary.  Dictionaries in Python look just like the hash in Ruby, so I had been operating under the assumption that they worked the same.  The main thing I remember from my class in Python was that dictionaries store things without order.  Therefore, when a problem came along in my Ruby homework that involved finding a hash value greater than 1 value but less than the next, I had written an answer assuming that I couldn't just go through the hash top to bottom until I found a range that fit my number.

It wasn't until I was comparing answers with my cohort that I realized their solution involved a simple .each loop, and I had to challenge my assumption!


As a side note, in trying to see whether Javascript's object literals were closer to hashes or dictionaries, I came across the line "JSON stands for JavaScript Object Notation," and suddenly calling something a JSON literal made absolute and total sense.  I love when things click!

So now I know that JSON literals and Python dictionaries both are unordered collections of key:value pairs, whereas a Ruby hash is an ordered collection. Yes, I came across a StackOverflow answer wherein I learned Python also has an OrderedDict which solves this problem, but in general it's good to know which will be ordered versus unordered.

If anyone is curious, the JSON enlightenment was courtesy of Oreilly.com.

Comments

  1. The orderedness of hashes is something I asked the EEs about when i was going through ignition, because if you read the docs it says that they're unordered, but they also can be looped through sequentially. And that's weird. Sebastian told me that one way to think of it is that an array is a type of hash, in which the key is the index. So, part of the orderedness of an array is that there is an index to define the order, which a hash doesn't have. Also! `{a: 'b', c: 'd'} == {c: 'd', a: 'b'}` wheras `['a', 'b', 'c', 'd'] != ['c', 'd', 'a', 'b']`

    ReplyDelete

Post a Comment

Thank you for reading my blog! I look forward to hearing from you.