功能
类似一个dict类,map[“abc”] = “aabbcc”; 直接就往map这个dict中添加了一个『abc』——『aabbcc』这个键值对。用method_missing来实现,MyOpenStruct类相当于这个dict类,直接往里塞实例方法和其对应的值。
class MyOpenStruct
def initialize
@attributes = {}
end
def method_missing(methodName, *args)
# method_missing 会对找不到的方法格式化
# 比如obj.nickName = "Focus"
# methodName 会接受到『nickName=』
attribute = methodName.to_s
if attribute =~ /.*=$/
# 相当于set方法
@attributes[attribute.chop] = args
else
# getting
@attributes[attribute]
end
end
end
obj = MyOpenStruct.new
obj.nickName = "CbdFocus"
puts obj.nickName
补充
String#chop
Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.
删除结尾的一个字符,如果结尾是换行就直接都删掉『UNIX/windows』,”“.chop 空String还是返回”“.
ter
"string\r\n".chop #=> "string"
"string\n\r".chop #=> "string\n"
"string\n".chop #=> "string"
"string".chop #=> "strin"
"x".chop.chop #=> ""