An Exercise in Metaprogramming with Ruby

An Exercise in Metaprogramming with Ruby

class DataRecord

def self.make(file_name)

# Open datafile and parse field names
data =
header = data.gets.chomp

# Get the classname, People, based on filename
class_name = File.basename(file_name,”.txt”).capitalize

# Define People class
# cf) To get a class already defined, call Object.get(“class_name”)
klass = Object.const_set(class_name,
names = header.split(“,”)

# Following block will define instance methods for People.
klass.class_eval do
attr_accessor *names

# initialize
define_method(:initialize) do |*values|
names.each_with_index do |name,i|
instance_variable_set(“@”+name, values[i])

# to_s
define_method(:to_s) do
str = “<#{self.class}:" names.each {|name| str << " #{name}=#{self.send(name)}" } str + ">”

# inspect is the same as to_s
alias_method :inspect, :to_s

# Define class method,
array = []
data =”.txt”)
data.gets # throw away header
data.each do |line|

# Getting data as an array
values = eval(“[#{line}]”)
array <<*values) end data.close array end klass end end # Preparing data output ="people.txt", "w") output << %{name,age,weight,height "Smith, John", 35, 175, "5'10" "Ford, Anne", 49, 142, "5'4" "Taylor, Burt", 55, 173, "5'10" "Zubrin, Candace", 23, 133, "5'6"} output.close # Look how DataRecord can be used DataRecord.make("people.txt") lines = puts lines.to_s puts lines[0].name [/code]

Similar Posts:

Post a Comment

Your email is never published nor shared.