Named Parameters in Ruby Structs

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

    The less you know, the better. No need to know whether the underlying data structure uses symbols or string, or even whether it can be addressed as a Hash. Just use the attribute setters:

    class KwStruct < Struct.new(:qwer, :asdf, :zxcv)
      def initialize *args
        opts = args.last.is_a?(Hash) ? args.pop : Hash.new
        super *args
        opts.each_pair do |k, v|
          self.send "#{k}=", v
        end
      end
    end
    

    It takes both positional and keyword arguments:

    > KwStruct.new "q", :zxcv => "z"
     => #
    

提交回复
热议问题