#!/usr/bin/env ruby flo = [ "dividuum", "syb", "fiji", "flowhase" ] # flos sind keine arrayss1! for i in 0..3 eval "flo#{i} = flo[#{i}]" puts "flo#{i} == \"" + eval("flo#{i}") + "\"" end
Dieses Perl (*duck*) kann ja keiner lesen! 1)
(eval-when (:compile-toplevel :load-toplevel :execute) (defvar *flo-sequence* #("dividuum" "syb" "fiji" "flowhase"))) (defmacro make-individual-flo-variables () (cons 'progn (loop for flo across *flo-sequence* for i from 0 collect `(defvar ,(read-from-string (format nil "*flo~d*" i)) ,flo)))) (make-individual-flo-variables) (dotimes (i 4) (format t "~&flo~d = ~a" i (eval (read-from-string (format nil "*flo~d*" i)))))
Und nun nochmal Ruby mit viel bloatigem Metaprogramming-Foo (Und etwas völlig anderes machend. Anm. v. mgr):
#!/usr/bin/env ruby class Flo def self.metaclass; class << self; self; end; end def self.traits(*arr) return @traits if arr.empty? attr_accessor *arr arr.each do |a| metaclass.instance_eval do define_method( a ) do |val| @traits ||= {} @traits[a] = val end end end class_eval do define_method( :initialize ) do self.class.traits.each do |k,v| instance_variable_set("@#{k}", v) end end end end traits :name, :skill, :notebook def to_s s = "#{self.class} is actually #{self.name} and is good at #{self.skill}\n\tHe loves hacking on his #{self.notebook}" end end class Flo0 < Flo name "dividuum" skill "DOOM" notebook "old Dell" end class Flo1 < Flo name "Peter" skill "math" notebook "IBM Thinkpad" end class Flo2 < Flo name "Fiji" skill "WOW" notebook "i have no idea" end class Flo3 < Flo name "flowhase" skill "hoppeln" notebook "hasIbook" end a = [ Flo0.new, Flo1.new, Flo2.new, Flo3.new ] a.each { |f| puts f }
1) Anmerkung zu: "Dieses Perl (*duck*) kann ja keiner lesen!"
Stimmt doch gar nicht! Ist ganz einfach:
map printf("%s = %s\n", [flo0..flo3]->[$_], [dividuum, syb, fiji, flowhase]->[$_]), 0..$#{@{[flo0..flo3]}};
(Kommentar von mgr: Genau, "0..$#{@{[flo0..flo3]}}" ... q.e.d. Danke für das gute Beispiel. Aber ernsthaft, es ging hier eben gerade *nicht* um Einzeiler, die will niemand.)
Und auch in python kann man Einzeiler schreiben:
print "\n".join(["%s = %s" % (k, v) for k, v in {"flo0":"dividuum", "flo1":"syb", "flo2":"fiji", "flo3":"flowhase"}.items()])