Named Parameters in Ruby Structs

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

    You could rearrange the ifs.

    class MyStruct < Struct
      # Override the initialize to handle hashes of named parameters
      def initialize *args
        # I think this is called a guard clause
        # I suspect the *args is redundant but I'm not certain
        return super *args unless (args.length == 1 and args.first.instance_of? Hash)
        args.first.each_pair do |k, v|
          # I can't remember what having the conditional on the same line is called
          self[k] = v if members.include? k
        end
      end
    end
    

提交回复
热议问题