A Hash Is A Function (Hash#to_proc)

Geplaatst door Michiel de Mare di, 26 feb 2008 00:42:00 GMT

Staring at the following code, I got an idea (inspired by Arc):

specialism_codes.map {|code| SPECIALISMS[code] }

Why do I have to create a block to map from a list of codes to a list of descriptions, when those codes and descriptions are all contained in a constant? Isn’t that what a Hash is, a mapping from a domain to a range? Isn’t that exactly the definition of a function in mathematics? Why then that block?

Anyway, I solved that pretty quickly:

class Hash
  def to_proc
    lambda {|x| self[x] }
  end
end

specialism_codes.map &SPECIALISMS

Geplaatst in ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning