Named Parameters in Ruby Structs

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

    Synthesizing the existing answers reveals a much simpler option for Ruby 2.0+:

    class KeywordStruct < Struct
      def initialize(**kwargs)
        super(*members.map{|k| kwargs[k] })
      end
    end
    

    Usage is identical to the existing Struct, where any argument not given will default to nil:

    Pet = KeywordStruct.new(:animal, :name)
    Pet.new(animal: "Horse", name: "Bucephalus") # => #  
    Pet.new(name: "Bob") # => # 
    

    If you want to require the arguments like Ruby 2.1+'s required kwargs, it's a very small change:

    class RequiredKeywordStruct < Struct
      def initialize(**kwargs)
        super(*members.map{|k| kwargs.fetch(k) })
      end
    end
    

    At that point, overriding initialize to give certain kwargs default values is also doable:

    Pet = RequiredKeywordStruct.new(:animal, :name) do
      def initialize(animal: "Cat", **args)
        super(**args.merge(animal: animal))
      end
    end
    
    Pet.new(name: "Bob") # => #
    

提交回复
热议问题