Ruby可选参数和多个参数 [英] Ruby Optional Parameters and Multiple Parameters

查看:67
本文介绍了Ruby可选参数和多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将方法的第一个参数设置为可选参数,后跟任意数量的args.例如:

I am trying to set the first argument to a method as being optional, followed by any number of args. For example:

def dothis(value=0, *args)

我遇到的问题是,看来这实际上是不可能的吗?当我调用dothis("hey", "how are you", "good")时,我希望它可以将value设置为default到0,但是它只是在制作value="hey".有什么办法可以实现这种行为?

The issue I am running into is that it doesn't seem like this is actually possible? When I call dothis("hey", "how are you", "good") I was hoping it would set value to default to 0, but instead it is just making value="hey". Is there any way to accomplish this behavior?

推荐答案

在Ruby中无法直接实现

This is not possible directly in Ruby

但是,有很多选择,具体取决于您对扩展参数所做的操作以及该方法的用途.

There are plenty of options though, depending on what you are doing with your extended params, and what the method is intended to do.

显而易见的选择是

1)使用哈希语法获取命名参数

1) Take named params using hash syntax

def dothis params
  value = params[:value] || 0
  list_of_stuff = params[:list] || []

Ruby在这方面有很好的调用约定,您无需提供井号{}括号

Ruby has nice calling convention around this, you don't need to provide the hash {} brackets

dothis :list => ["hey", "how are you", "good"]

2)将值移到末尾,并为第一个参数获取一个数组

2) Move value to the end, and take an array for the first param

def dothis list_of_stuff, value=0

这样称呼:

dothis ["hey", "how are you", "good"], 17

3)使用代码块提供列表

3) Use a code block to provide the list

dothis value = 0
  list_of_stuff = yield

这样称呼

dothis { ["hey", "how are you", "good"] }

4)Ruby 2.0引入了命名哈希参数,该参数为您处理了很多选项1:

4) Ruby 2.0 introduced named hash parameters, which handle a lot of option 1, above for you:

def dothis value: 0, list: []
  # Local variables value and list already defined
  # and defaulted if necessary

与(1)相同的调用方式:

Called same way as (1):

dothis :list => ["hey", "how are you", "good"]

这篇关于Ruby可选参数和多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆