加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Ruby中创建一个Expando对象

发布时间:2020-12-17 03:58:35 所属栏目:百科 来源:网络整理
导读:有没有更好的方法来编写这个Expando类?它的编写方式不起作用. 我正在使用 Ruby 1.8.7 起始代码来自https://gist.github.com/300462/3fdf51800768f2c7089a53726384350c890bc7c3 class Expando def method_missing(method_id,*arguments) if match = method_i
有没有更好的方法来编写这个Expando类?它的编写方式不起作用.
我正在使用 Ruby 1.8.7

起始代码来自https://gist.github.com/300462/3fdf51800768f2c7089a53726384350c890bc7c3

class Expando
    def method_missing(method_id,*arguments)
        if match = method_id.id2name.match(/(w*)(s*)(=)(s*)(.*)/)
              puts match[1].to_sym # think this was supposed to be commented 
              self.class.class_eval{ attr_accessor match[1].to_sym } 
              instance_variable_set("#{match[1]}",match[5])
        else
              super.method_missing(method_id,*arguments)
        end  
    end    
end

person = Expando.new 
person.name = "Michael"
person.surname = "Erasmus"
person.age = 29

解决方法

写它最简单的方法就是不要写它! :)查看标准库中包含的 OpenStruct类:

require 'ostruct'

record = OpenStruct.new
record.name    = "John Smith"
record.age     = 70
record.pension = 300

如果我打算写它,我会这样做:

# Access properties via methods or Hash notation
class Expando
  def initialize
    @properties = {}
  end
  def method_missing( name,*args )
    name = name.to_s
    if name[-1] == ?=
      @properties[name[0..-2]] = args.first
    else
      @properties[name]
    end
  end
  def []( key )
    @properties[key]
  end
  def []=( key,val )
    @properties[key] = val
  end
end

person = Expando.new
person.name = "Michael"
person['surname'] = "Erasmus"
puts "#{person['name']} #{person.surname}"
#=> Michael Erasmus

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读