I really like Ruby, and I really like how the Prototype library makes javascript more Ruby-like. Ruby’s Hash provides a number of convenient methods that Prototype doesn’t ship with. Here is a small extension that borrows a little from Ruby.

Hash.prototype = Object.extend(Hash.prototype, {
  hasKey: function(key) {
    return this._object.hasOwnProperty(key);
  fetch: function(key, fallback) {
    return (this.hasKey(key) ? this.get(key) : fallback);
  getWithDefault: function(key, fn) {
    return (this.hasKey(key) ? this.get(key) : this.set(key, fn()));
  getOrSet: function(key, val) {
    return (this.hasKey(key) ? this.get(key) : this.set(key, val));

First, it should be simple to check for the existence of a key in a Hash, whether or not that key contains a falsy value. Since Prototype 1.6, a Hash’s inner object is stored independently of the Hash objects real keys, such as its methods, so the hasKey implementation will only work with Prototype 1.6.

Next up is fetch, which behaves the same as Ruby’s fetch, returning the value present in the Hash for the provided key if a value exists, and providing your supplied alternative otherwise.

getOrSet does essentially the same thing, but adds the alternative value to the Hash if no value was previously present.

Finally, getWithDefault takes a functional 2nd argument which is invoked only if the provided key is not present in the Hash, which is useful for memoizing expensive work.

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.