代码之家  ›  专栏  ›  技术社区  ›  f00860

Ruby中所有属性的“magic constructor”

  •  2
  • f00860  · 技术社区  · 14 年前

    有没有一种方法可以设置默认的初始化方法而不写下来?

    class DataClass
      attr_accessor :title, :description, :childs
      def hasChilds?
        @childs.nil?
      end
    end
    

    我想用标准的初始属性初始化这个类。像这样:

    $> a = DataClass.new(:title => "adsf", :description => "test")
    $> a.title # --> "asdf"
    

    有这样的解决办法吗?

    5 回复  |  直到 14 年前
        1
  •  2
  •   Jonas Elfström    14 年前

    取决于你想要达到的目标,你可能会使用 OpenStruct

    a = OpenStruct.new(:title => "adsf", :description => "test")
    >> a.title
    =>> "adsf"
    
        2
  •  4
  •   rjk    14 年前

    一种选择是使用 Struct 作为你班的基础。例如:

    class DataClass < Struct.new(:title, :description, :childs)
      def has_childs?
        @childs.nil?
      end
    end
    
    a = DataClass.new('adsf', 'description')
    puts a.title
    

    现在参数的顺序很重要。

        3
  •  2
  •   halfdan    14 年前

    你可以用 this gem 然后简单地做:

    require 'zucker/ivars'
    
    def initialize(variable1, variable2)
      instance_variables_from binding # assigns @variable1 and @variable2
    end
    

    “扎克”宝石也允许你使用哈希!看看 example .

        4
  •  2
  •   shawn42    14 年前

    我相信建造宝石完全按照你想要的做: http://atomicobject.github.com/constructor/

      require 'constructor'
    
      class Horse
        constructor :name, :breed, :weight
      end
      Horse.new :name => 'Ed', :breed => 'Mustang', :weight => 342
    
        5
  •  0
  •   mahemoff    11 年前

    Hashie 对这个很有用。

    horse = Hashie::Mash.new(name: 'Ed', breed: 'Mustang', weight: 342)
    horse.name    # 'Ed'
    horse[:name]  # 'Ed'
    horse['name'] # 'Ed'
    

    您也可以使用它的dash类来创建具有受限属性名称的真实类。以及其他一些有用的数据结构。