Named Parameters in Ruby Structs

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

    If your hash keys are in order you can call the splat operator to the rescue:

    NavLink = Struct.new(:name, :url, :title)
    link = { 
      name: 'Stack Overflow', 
      url: 'https://stackoverflow.com', 
      title: 'Sure whatever' 
    }
    actual_link = NavLink.new(*link.values) 
    # 
    

提交回复
热议问题