Reputation: 2859
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
Upvotes: 14
Views: 6219
Reputation: 2226
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">
Upvotes: 23
Reputation: 110675
my_struct = MyStruct.new(fname: 'first', lname: 'last')
is the same as
my_struct = MyStruct.new({ fname: 'first', lname: 'last' })
#=> #<struct MyStruct fname={:fname=>"first", :lname=>"last"}, lname=nil>
(one argument) so fname
is set equal to the argument and lname
is set to nil
, in the same way that x, y = [2]; x #=> 2; y #=> nil
.
This is because Ruby allows one to omit the braces when a hash is the argument of a method.
You may wish to search SO for related questions such as this one.
Upvotes: 2