Posts for June, 2005

Spotlight on Ruby

A nifty Spotlight plugin so you can search Ruby code. Via MacOS X Hints

In other news, I just got 186 lines in Tetris! (old-school Gameboy, the only way to play) What's your highest?

Hash#remap

Since we're mapping Array's around, we might as well do Hash's too. (And yes, I actually needed these)

class Hash

  # remap the keys and/or values of a hash to a new hash
  def remap(hash={})
    each { |k,v| yield hash, k, v }
    hash
  end

  # remap the keys and/or values of a hash to self. Probably wouldn't
  # do the keys unless providing aliases.
  def remap!(&block)
    remap self, &block
  end

end

I just know you had to do this recently:

stuff = {"a"=>5, "b"=>10, "c"=>15}
stuff.remap do |h, k, v|
  h[(k * 2).to_sym] = v * 2
end
=> {:aa=>10, :bb=>20, :cc=>30}

Array#to_h redux

Since the last post I've been really busy writing code, moving into a new house and being sick. So first off, apologies for the lack of content here.

Next. Confession. I made a fatal flaw when coming up with Array#to_h. I didn't need it. Well, I needed something but it wasn't exactly what that method turned out to be. I got caught up trying to make a cool one liner (but learned a lot about Hash while doing it).

Turns out sometimes I wanted to play with keys, sometimes values and sometimes both. Turns out all I needed was something simple like this:

class Array

  # yield each value of the array and a hash, return the hash
  def to_h(hash={})
    each { |value| yield hash, value }
    hash
  end

end

Because really the only thing that bugged me about doing it inline was having to return the hash.. that dangling return value just never feels right. This tightens it up just enough.

def map_something(array)
  array.to_h do |hash, value|
    hash[value.to_sym] = transform_value value
  end
end

By the way, making hash a parameter to the method lets you do cool things like assign default values to all new elements. Another pointless example:

h = Hash.new { |hash,key| hash[key] = 5 }
[1,2,3].to_h(h) do |hash,value|
  hash[value] *= value
end
=> {1=>5, 2=>10, 3=>15}

So, one dangling issue. Should this be a method of Array or Enumerable? If Enumerable it should probably be overridden for Hash as Hash#to_h should simply return self.

  • June 8, 2005
  • Dealing with ruby