简体   繁体   English

Ruby-如何将单个参数传递给带有长参数列表的方法?

[英]Ruby - how to pass a single argument to a method with long list of arguments?

Is there a way to pass a single argument to a ruby function that has only optional parameters? 有没有办法将单个参数传递给仅具有可选参数的ruby函数?

For instance, I want to pass ignoreAlreadyCrawled = true in the method below, and use the default parameter values for everything else. 例如,我想在下面的方法中传递ignoreAlreadyCrawled = true,并对其他所有参数使用默认参数值。 But since it's the last parameter, I have to do call crawl(nil, nil, nil, false, nil, false, nil, false, [], true), which is verbose, and ugly. 但是由于它是最后一个参数,所以我必须调用crawl(nil,nil,nil,false,nil,false,nil,false,[],true),这是冗长且丑陋的。

Method: 方法:

def crawl(url = nil, proxy = nil, userAgent = nil, post = false, postData = nil, image = false, imageFilename = nil, forceNoUserAgent = false, ignoreSubDomains = [], ignoreAlreadyCrawled = false)   
        #..logic here
    end      

This is possible for ruby >= 2.0 with keyword arguments. 对于使用关键字参数的ruby> = 2.0,这是可能的。 In that case, you have to modify the method signature as follows (basically change = to : ): 在这种情况下,必须修改如下方法签名(基本不变=: ):

def crawl(url: nil, proxy: nil, userAgent: nil, post: false, postData: nil, image: false, imageFilename: nil, forceNoUserAgent: false, ignoreSubDomains: [], ignoreAlreadyCrawled: false)   
    #..logic here
end

And it will work as expected: 它将按预期工作:

crawl(ignoreAlreadyCrawled: true)

Please see article for more examples: https://robots.thoughtbot.com/ruby-2-keyword-arguments 请参阅文章以获取更多示例: https : //robots.thoughtbot.com/ruby-2-keyword-arguments

When you have more than two or three arguments, the preferred pattern is to use a Hash of options instead. 当您拥有两个或三个以上的参数时,首选模式是使用选项的哈希值。

I would redefine this method as follows: this is similar to Pawel's but more readable, i think: 我将重新定义此方法如下:这与Pawel的相似,但更易读,我认为:

def crawl(options={})
  defaults = { url: nil, 
               proxy: nil, 
               userAgent: nil, 
               post: false, 
               postData: nil, 
               image: false, 
               imageFilename: nil, 
               forceNoUserAgent: false, 
               ignoreSubDomains: [], 
               ignoreAlreadyCrawled: false
             }
    options = defaults.merge(options)
    #..logic here

end

You could omit from defaults all options that have nil as their default, as an undefined option will come out as nil anyway. 您可以从默认值中忽略所有以nil为默认值的选项,因为无论如何,未定义的选项都会显示为nil。 But, having them there acts as documentation for which options can be passed. 但是,在那里有它们充当可以传递选项的文档。

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

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