Named Parameters in Ruby Structs

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

    this doesn't exactly answer the question but I found it to work well if you have say a hash of values you wish to structify. It has the benefit of offloading the need to remember the order of attributes while also not needing to subClass Struct.

    MyStruct = Struct.new(:height, :width, :length)

    hash = {height: 10, width: 111, length: 20}

    MyStruct.new(*MyStruct.members.map {|key| hash[key] })

提交回复
热议问题