Named Parameters in Ruby Structs

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

    Based on @Andrew Grimm's answer, but using Ruby 2.0's keyword arguments:

    class Struct
    
      # allow keyword arguments for Structs
      def initialize(*args, **kwargs)
        param_hash = kwargs.any? ? kwargs : Hash[ members.zip(args) ]
        param_hash.each { |k,v| self[k] = v }
      end
    
    end
    

    Note that this does not allow mixing of regular and keyword arguments-- you can only use one or the other.

提交回复
热议问题