Named Parameters in Ruby Structs

后端 未结 12 1669
小蘑菇
小蘑菇 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:44

    Ruby 2.x only (2.1 if you want required keyword args). Only tested in MRI.

    def Struct.new_with_kwargs(lamb)
      members = lamb.parameters.map(&:last)
      Struct.new(*members) do
        define_method(:initialize) do |*args|
          super(* lamb.(*args))
        end
      end
    end
    
    Foo = Struct.new_with_kwargs(
      ->(a, b=1, *splat, c:, d: 2, **kwargs) do
        # must return an array with values in the same order as lambda args
        [a, b, splat, c, d, kwargs]
      end
    )
    

    Usage:

    > Foo.new(-1, 3, 4, c: 5, other: 'foo')
    => #"foo"}>
    

    The minor downside is that you have to ensure the lambda returns the values in the correct order; the big upside is that you have the full power of ruby 2's keyword args.

提交回复
热议问题