class DataSource
def get_cpu_info
“cpu8001”
end
def get_cpu_price
101
end
def get_mouse_info
"mouse241"
end
def get_mouse_price
40
end
end
DataSource.new.methods.grep(/^get_(.+?)_info$/) do |meth|
puts “—#{meth}—”
end
–output:–
—get_cpu_info—
—get_mouse_info—
class Computer
def initialize(an_id, data_source)
@id = an_id
@ds = data_source
@ds.methods.grep(/^get_(.+?)_info$/) do
puts "-->#{$1}<---"
Computer.send(:define_method, $1.to_sym) do
puts "****" + $1 + "****" #***NIL NIL NIL NIL
info = @ds.send("get_#{$1}_info".to_sym)
price = @ds.send("get_#{$1}_price".to_sym)
alert = ""
if price > 100
alert = "*"
end
return "#{alert}#{info} #{price}"
end
end
end
end
comp1 = Computer.new(1, DataSource.new)
puts comp1.mouse
–output:–
Line 32:in +': can't convert nil into String (TypeError) from t.rb:32:in
mouse’
from t.rb:52