Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Ruby Structs with Keyword arguments

Tags:

ruby

struct

Ruby version: 2.3.1

It does not appear that Ruby Structs can be declared using keyword params. Is there a way to do this within Struct?

Example:

MyStruct = Struct.new(:fname, :lname)
=> MyStruct

my_struct = MyStruct.new(fname: 'first', lname: 'last')
=> <struct MyStruct fname={:fname=>"first", :lname=>"last"}, lname=nil>

my_struct.fname
=> {:fname=>"first", :lname=>"last"}

my_struct.lname
=> nil
like image 615
user3162553 Avatar asked Jan 11 '17 23:01

user3162553


1 Answers

With Ruby 2.5, you can set the keyword_init option to true.

MyStruct = Struct.new(:fname, :lname, keyword_init: true)
# => MyStruct(keyword_init: true)
irb(main):002:0> my_struct = MyStruct.new(fname: 'first', lname: 'last')
# => #<struct MyStruct fname="first", lname="last">
like image 156
Martinos Avatar answered Oct 01 '22 03:10

Martinos