Idiomatic object creation in ruby

前端 未结 6 1954
春和景丽
春和景丽 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条回答
  •  萌比男神i
    2020-12-01 15:33

    You could use an object as param.

    class Foo
      attr_accessor :param
    
      def initialize(p)
        @param = p
      end
    end
    
    f = Foo.new
    f.param.bar = 1
    f.param.bax = 2
    

    This does not save much lines in this case but it will if your class has to handle a large number of param. You could also implement a set_param and get_param method if you want to keep your @param var private.

提交回复
热议问题