Named Parameters in Ruby Structs

后端 未结 12 1625
小蘑菇
小蘑菇 2020-12-29 20:12

I\'m pretty new to Ruby so apologies if this is an obvious question.

I\'d like to use named parameters when instantiating a Struct, i.e. be able to specify which ite

12条回答
  •  囚心锁ツ
    2020-12-29 20:40

    A solution that only allows Ruby keyword arguments (Ruby >=2.0).

    class KeywordStruct < Struct
      def initialize(**kwargs)
        super(kwargs.keys)
        kwargs.each { |k, v| self[k] = v }
      end
    end
    

    Usage:

    class Foo < KeywordStruct.new(:bar, :baz, :qux)
    end
    
    
    foo = Foo.new(bar: 123, baz: true)
    foo.bar  # --> 123
    foo.baz  # --> true
    foo.qux  # --> nil
    foo.fake # --> NoMethodError
    

    This kind of structure can be really useful as a value object especially if you like more strict method accessors which will actually error instead of returning nil (a la OpenStruct).

提交回复
热议问题