用method_missing 实现的 OpenStruct

功能

类似一个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       #=> ""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值