【问题标题】:Is there a way to force usage of named parameters instead of your standard function_name(var, var)?有没有办法强制使用命名参数而不是标准的 function_name(var, var)?
【发布时间】:2012-01-11 19:00:47
【问题描述】:

我真的很喜欢命名参数,因为它们极大地提高了我的代码的可读性。

Ruby 使用带有哈希的伪命名参数,我已经使用该技术实现了一些方法,但是将这三行添加到每个带有参数的方法中会变得很麻烦:

def something_does_something_with(parameters = {})
  default_params = {:some => option, :another => something}
  parameters = default_params.merge(parameters)
  ...
end

或者方法头可以是这样的:

def something_does_something_with(parameters = {:some => option, :another => something})

但是我认为如果我提供任何参数,它会覆盖整个默认哈希。

当我使用 Objective-C 时,命名变量是我在编程世界中最喜欢的东西。

有没有办法修改 Ruby 查看方法头的默认方式,这样就需要命名参数,或者至少更容易?

【问题讨论】:

  • 实现与此类似的一种方法是使用上面的方法,它将哈希作为参数,然后使用类似于命名参数的哈希键。如果您有上述方法,则对该方法的调用可能如下所示:something_does_something_with(:param1 => 'value1', :param2 => 'value2')(等)。这并不完全相同,但它在 Ruby 中是非常普遍的做法,并且基本上实现了相同的目标。

标签: ruby syntax semantics


【解决方案1】:

您绝对不能使用第二个示例,因为它仅在您传递全套参数时才有效。

参考您的第一个示例,您可以像这样简短:

def something_does_something_with(parameters = {})
  parameters = {:some=>option,:another=>something}.merge(parameters)
  ...
end

最后,命名参数计划在 Ruby 的下一个版本 - Ruby 2.0 中实现

【讨论】:

  • Ruby 2.0 将成为最好的 Ruby。 o.o
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 2018-11-30
  • 2011-01-17
  • 2016-11-12
  • 1970-01-01
相关资源
最近更新 更多