是否有更多的“干”方式来做以下的ruby?
#!/usr/bin/env ruby class Volume attr_accessor :name,:size,:type,:owner,:date_created,:date_modified,:iscsi_target,:iscsi_portal SYSTEM = 0 DATA = 1 def initialize(args={:type => SYSTEM}) @name = args[:name] @size = args[:size] @type = args[:type] @owner = args[:owner] @iscsi_target = args[:iscsi_target] @iscsi_portal = args[:iscsi_portal] end def inspect return {:name => @name,:size => @size,:type => @type,:owner => @owner,:date_created => @date_created,:date_modified => @date_modified,:iscsi_target => @iscsi_target,:iscsi_portal => @iscsi_portal } end def to_json self.inspect.to_json end
结束
解决方法
每当你看到很多这样的东西,通常你可以把它全部变成单数组:
class Volume ATTRIBUTES = [ :name,:iscsi_portal ].freeze ATTRIBUTES.each do |attr| attr_accessor attr end SYSTEM = 0 DATA = 1 DEFAULTS = { :type => SYSTEM }.freeze def initialize(args = nil) # EDIT # args = args ? DEFAULTS : DEFAULTS.merge(args) # Original args = args ? DEFAULTS.merge(args) : DEFAULTS ATTRIBUTES.each do |attr| if (args.key?(attr)) instance_variable_set("@#{attr}",args[attr]) end end end def inspect ATTRIBUTES.inject({ }) do |h,attr| h[attr] = instance_variable_get("@#{attr}") h end end def to_json self.inspect.to_json end end
之后操纵实例变量是非常简单的.