Idiomatic object creation in ruby

前端 未结 6 1956
春和景丽
春和景丽 2020-12-01 14:39

In ruby, I often find myself writing the following:

class Foo
  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>
         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-01 15:18

    I asked a duplicate question, and suggested my own answer there, expecting for a better one, but a satisfactory one did not appear. I will post my own one.

    Define a class method like the following along the spirit of attr_accessor, attr_reader, attr_writer methods.

    class Class
        def attr_constructor *vars
            define_method("initialize") do |*vals|
                vars.zip(vals){|var, val| instance_variable_set("@#{var}", val)}
            end
        end
    end
    

    Then, you can use it like this:

    class Foo
        attr_constructor :foo, :bar, :buz
    end
    
    p Foo.new('a', 'b', 'c')      # => #
    p Foo.new('a', 'b', 'c', 'd') # => #
    p Foo.new('a', 'b')           # => #
    

提交回复
热议问题