Idiomatic object creation in ruby

前端 未结 6 1959
春和景丽
春和景丽 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:21

    I sometimes do

    @bar, @baz = bar, baz
    

    Still boilerplate, but it only takes up one line.

    I guess you could also do

    ["bar", "baz"].each do |variable_name|
      instance_variable_set(:"@#{variable_name}", eval(variable_name))
    end
    

    (I'm sure there's a less dangerous way to do that, mind you)

    https://bugs.ruby-lang.org/issues/5825 is a proposal to make the boilerplate less verbose.

提交回复
热议问题