hoodwink.d enhanced


Learning? Read Split-s. #

by why in cult

Split-s, a nice blog for getting down some basic Ruby concepts. The code here on RedHanded can be pretty heavy handed sometimes—I’m completely out of touch with each of your pressing needs—so I’ll defer to split-s when it comes to topics such as conditional initialization. Which culminates in an explanation of this snip:

 def addToList(key, value)
   (@map[key] ||= []) << value

Martin also codes in Java—expect some comparisons. If you lack know-how on duck typing, take a gander at yesterday’s Quack, Quack.

said on 02 Feb 2005 at 11:32
def initialize
  @map = Hash.new { |h,k| h[k] = [] }

def attToList(key, val)
  @map[key] << val

much more readable, doncha think?

said on 02 Feb 2005 at 12:04

In some ways yes. But is there some sort of advantage, aside from speed, to the other method?

said on 02 Feb 2005 at 13:34

Sometimes you can’t define initialize by yourself. Modules in their Mix-In roles have a hard-time initializing stuff, for example, which is why they usually use the lazy initialisation technic.

Another advantage might be that you can skip initializing stuff that you aren’t going to need anyway. Which might be important if said initialization is very expensive.

Comments are closed for this entry.