We have tooltips, let’s use them! Smart Select List
Jun 15

create_many_arrays :foo, :bar, :baz

Tech Add comments

A bunch of lazy programmers that I know looked at some code that had a lot of:

@foo = []
@bar = []
@baz = []

Instead they wanted to do:

create_many_arrays :foo, :bar, :baz

NOTE: watching someone do “foo = bar = baz = []” is fun :)

So:

def create_many_arrays(*arraynames)
params = arraynames.join ','
arrays = ''
attrs = ''

arraynames.each do |name|
thename = name.to_s
arrays += "@#{thename} = []\n"
attrs += "attr_accessor :#{name}\n"
end

code = <<-END_OF_CODE
alias :__dion__initialize :initialize
#{attrs}

def initialize
__dion__initialize
#{arrays}
end

def initialize(*incoming)
__dion__initialize *incoming
#{arrays}
end
END_OF_CODE

class_eval code
end

class Foo
create_many_arrays :foo, :bar
end

f = Foo.new
f.foo
f.foo << 1
f.foo

class Bar
attr_accessor :a

def initialize(a)
@a = a
end

create_many_arrays :foo, :bar
end

After a broken impl like this, you then realise that there is no real reason to want to do this, and your own code is broken if you want data structures like this.

One Response to “create_many_arrays :foo, :bar, :baz”

  1. Rob Sanheim Says:

    looks to me like there is a real class trying to get out of all those arrays…

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: What are the first four letters in the word British?