How to change the default value of a Struct attrib

2020-02-10 11:20发布

According to the documentation unset attributes of Struct are set to nil:

unset parameters default to nil.

Is it possible to specify the default value for particular attributes?

For example, for the following Struct

Struct.new("Person", :name, :happy)

I would like the attribute happy to default to true rather than nil. How can I do this? If I do as follows

Struct.new("Person", :name, :happy = true)

I get

-:1: syntax error, unexpected '=', expecting ')'
Struct.new("Person", :name, :happy = true)
                                    ^
-:1: warning: possibly useless use of true in void context

标签: ruby
7条回答
欢心
2楼-- · 2020-02-10 12:04

Following @rintaun's example you can also do this with keyword arguments in Ruby 2+

A = Struct.new(:a, :b, :c) do
  def initialize(a:, b: 2, c: 3); super end
end

A.new
# ArgumentError: missing keyword: a

A.new a: 1
# => #<struct A a=1, b=2, c=3> 

A.new a: 1, c: 6
# => #<struct A a=1, b=2, c=6>

UPDATE

The code now needs to be written as follows to work.

A = Struct.new(:a, :b, :c) do
  def initialize(a:, b: 2, c: 3)
    super(a, b, c)
  end
end
查看更多
登录 后发表回答