简体   繁体   English

在 Ruby 中,如何使用默认参数或指定参数调用方法而不重复代码?

[英]In Ruby, how can you invoke a method using its default argument or with a specified argument without repeating code?

Say I have a ruby method:假设我有一个 ruby​​ 方法:

def blah(foo=17)
   ...
end

In code I want to invoke blah with a specific argument "blah(a)" or invoke blah using its default argument "blah()" Is there any way to do that without specifying the method name twice?在代码中,我想使用特定参数“blah(a)”调用 blah 或使用其默认参数“blah()”调用 blah 有没有办法在不指定方法名称的情况下两次指定方法名称? I'm trying to avoid:我试图避免:

if a.nil?
  blah()
else
  blah(a)
end

Because it makes the code look more complicated than it is.因为它使代码看起来比实际更复杂。 Best I can come up with (didn't test) is:我能想到的最好的(没有测试)是:

args=[]
args << a unless a.nil?
a.send :blah, args

I just tried a few ways, and didn't find any, but if you find yourself doing this a lot, I wonder of the benefit of using a default parameter that way.我只是尝试了几种方法,但没有找到任何方法,但是如果您发现自己经常这样做,我想知道以这种方式使用默认参数的好处。 Try this instead:试试这个:

def blah(foo=nil)
  foo ||= 17
  puts foo
end

blah()
a = nil
blah(a)
a = 20
blah(a)

This will output:这将输出:

17
17
20

我不喜欢这个答案,但我想它有效:

blah( *[a].compact )

It's hard to say without knowing what the actual problem being solved is, but I have a feeling something like this would work best:在不知道要解决的实际问题是什么的情况下很难说,但我觉得这样的事情最有效:

blah(a || 17)

This statement seems to more clearly express its intent, without leaving the reader to lookup the definition of the blah function in order to work out what the default is.这个语句似乎更清楚地表达了它的意图,没有让读者查找blah函数的定义以找出默认值是什么。

I was looking for the same.我正在寻找相同的。 (I think it is almost a bug in Ruby specs) I think I will solve this in other way ussing the option hash. (我认为这几乎是 Ruby 规范中的一个错误)我想我会使用选项哈希以其他方式解决这个问题。

def foo(options={})
  bar = options.delete(:bar) || :default
  puts bar
end

foo 
#=> default

foo :bar => :something
#=> something

a = nil
foo :bar => a
#=> default

It is more extensible and is readable for any rubyst.它更具可扩展性,并且对于任何 ruby​​st 都是可读的。

I vote for我投赞成票

def blah(foo = nil)
    foo ||= 17
end

too.也。

But if you would like to distinguish between the nil -value and no-argument situations, I suggest using a block like so:但是如果你想区分nil值和无参数的情况,我建议使用像这样的块:

def blah
    foo = block_given? ? yield : 17
end

blah         #=> 17
blah { nil } #=> nil
blah { 71 }  #=> 71

In ruby everything has a return value.在 ruby​​ 中,一切都有返回值。 So if also has a return value.所以if也有返回值。 The following method works with any number of arguments.以下方法适用于任意数量的参数。 The * expands an array so the array elemnts are individual arguments. *扩展数组,因此数组元素是单独的参数。

blah(*
  if a.nil?
    []
  else
    [a]
  end
)

You don't have to indent it this way, but this looked like the indentation to make it clearest.您不必以这种方式缩进,但这看起来像是最清晰的缩进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM