在下面的代码中,必须重复命名参数,是否可以缩短表达式?
struct Figure
getter id : String
getter hash : String
getter title : String
def initialize(@id, @hash, @title)
end
end
id = "Figure 1", hash = "123", title = "Some figure"
Figure.new id: id, hash: hash, title: title
类似于下面的代码,但仍将其命名为位置错误?
Figure.new id, hash, title
或者也许
Figure.new{ id, hash, title }
我不知道一种缩短方法。
我认为当将局部变量的名称与方法参数的名称绑定在一起时,这将是一种危险的语义,因为在一个地方更改事物会在另一个地方产生不可预见的影响。
对于大多数用例,使用位置参数应该没问题。而且,如果要跳过某些参数,可以只组合位置参数和命名参数。