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
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With