--方法
#将字符串转换成符号
String # to_sym()
String # intern()
#将符号转换成字符串
Symbol # to_s()
Symbol # id2name()
#动态定义方法
define_method
例子1:
class MyClass
define_method :my_method do |my_arg|
puts my_arg * 7
end
end
obj = MyClass.new
obj.send('my_method'.to_sym,7)
例子2:
class TestClass
def get_mode_info(name)
"#{name}_1"
end
def get_code_info(name)
"#{name}_2"
end
end
class MyClass
def init(cl)
@objTest = cl
@objTest.methods.grep(/^get_(.*)_info/){
MyClass.define_component($1)
}
end
def self.define_component(name)
define_method(name){
@objTest.send("get_#{name}_info",name)
}
end
end
obj = MyClass.new
obj.init(TestClass.new)
puts obj.mode
method_missing() 幽灵方法
例
class MyOpenStruct
def initialize
@attributes = {}
end
def method_missing(name, *args)
attribute = name.to_s
if attribute =~ /=$/
@attributes[attribute.chop] = args
else
@attributes[attribute]
end
end
end
ice = MyOpenStruct.new
ice.flavor = ["vanilla","test"]
puts ice.flavor
puts 'ice'.methods.grep(/^chop/)
respond_to? 判断方法是否存在
例
class TargetClass
def test_info
'test'
end
end
class TestClass
def initialize(classN)
@obj = classN
end
def method_missing(name,*args)
super if !@obj.respond_to?("#{name}_info")
puts @obj.send("#{name}_info")
end
def respond_to?(method)
@obj.respond_to?("#{method}_info") || super
end
def testT
end
end
obj = TestClass.new(TargetClass.new)
puts obj.respond_to?("test".to_sym)
puts obj.respond_to?(:testT)
#移除继承的方法
undef_method
例
class MyTest
instance_methods.each do |m|
undef_method m unless m.to_s =~ /^_|method_missing|respond_to?/
end
def method_missing(name , *args)
"#{name}(#{args.join(',')})"
end
end
puts MyTest.display
obj = MyTest.new
puts obj.display
yield 调用block
block_given? 判断是否有block回调
例子:
class TCl
def a_method
return yield if block_given?
'no block'
end
end
obj = TCl.new
puts obj.a_method{'do test'}
puts obj.a_method