Named Parameters in Ruby Structs

后端 未结 12 1676
小蘑菇
小蘑菇 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条回答
  •  梦毁少年i
    2020-12-29 20:39

    If you do need to mix regular and keyword arguments, you can always construct the initializer by hand...

    Movie = Struct.new(:title, :length, :rating) do
      def initialize(title, length: 0, rating: 'PG13')
        self.title = title
        self.length = length
        self.rating = rating
      end
    end
    
    m = Movie.new('Star Wars', length: 'too long')
    => #
    

    This has the title as a mandatory first argument just for illustration. It also has the advantage that you can set defaults for each keyword argument (though that's unlikely to be helpful if dealing with Movies!).

提交回复
热议问题