Metaprogramming Basics
Introspection
Ruby objects can report information about their classes and methods.
Introspection
introspection.rb
class Calculator
def add
"add"
end
def subtract
"subtract"
end
end
prefix =
methods = Calculator.public_instance_methods(false).map(&:to_s).sort
matches = methods.select { |method_name| method_name.start_with?(prefix) }
matches_text = matches.join("/")
puts "class=#{Calculator.name}"
puts "prefix=#{prefix}"
puts "matches=#{matches_text}"
puts "count=#{matches.length}"
class Calculator
def add
"add"
end
def subtract
"subtract"
end
end
prefix =
methods = Calculator.public_instance_methods(false).map(&:to_s).sort
matches = methods.select { |method_name| method_name.start_with?(prefix) }
matches_text = matches.join("/")
puts "class=#{Calculator.name}"
puts "prefix=#{prefix}"
puts "matches=#{matches_text}"
puts "count=#{matches.length}"
class Calculator
def add
"add"
end
def subtract
"subtract"
end
end
prefix =
methods = Calculator.public_instance_methods(false).map(&:to_s).sort
matches = methods.select { |method_name| method_name.start_with?(prefix) }
matches_text = matches.join("/")
puts "class=#{Calculator.name}"
puts "prefix=#{prefix}"
puts "matches=#{matches_text}"
puts "count=#{matches.length}"
introspection
Introspection means asking code about its own shape, such as which methods a class defines.