转至:http://www.skorks.com/2009/08/method-arguments-in-ruby/
Method arguments in Ruby are interesting because of the great flexibility in how you’re allowed to supply them to methods. Ruby method arguments can loosely be broken up into two categories, required arguments and optional arguments. However, I like to break them up into three categories (I hope it will become clear by the end of this post why I do so):
- required arguments
- arguments with default values
- optional arguments
Required Arguments
These are just your stock standard method arguments, e.g.:
def some_method(a, b) end
To call the method above you will need to supply two arguments to the method call, e.g.:
some_method(25,"hello")
Pretty basic stuff, nothing much to see here, moving on :).
Arguments With Default Value
In Ruby you can supply a default value for an argument. This means that if a value for the argument isn’t supplied, the default value will be used instead, e.g.:
def some_method(a, b, c=25) end
You may call the method above in one of two ways:
some_method(25,"hello")
or
some_method(25,"hello", 48)
In the first case you don’t supply a value for the third parameter, so it’s default value (i.e. 25) will be used in the method body. In the second case you do supply a value, so it will be used in place of the default value. Therefore, arguments with default values are a type of optional argument.
Optional Arguments
If you want to decide at runtime how many – if any – arguments you will supply to a method, Ruby allows you to do so. You need to use a special notation when you define the method, e.g.:
def some_method(*p) end
You can call the above method with any number of arguments (including none), e.g.:
some_method
or
some_method(25)
or
some_method(25,"hello", 45, 67)
All of those will work. If no arguments are supplied, then p will be an empty array, otherwise, it will be an array that contains the values of all the arguments that were passed in.
So, far it is all pretty basic stuff. The real fun begins when you need to mix and match the three types of arguments together.
Mixing And Matching The Various Types Of Arguments
What happens when you start to mix required arguments with optional arguments? Do they have to be in any specific order, and what gets assigned to what?
The easiest case is mixing a number of required arguments with the fully optional argument (i.e. the * notation), e.g.:
def some_method(a, b, *p) end
You can call the above method with two or more values. The first two values will be assigned to arguments a and b, the rest will be assigned to p as an array, pretty simple. But, what if I wanted to do the following:
def some_method(a, b, *p, q) end
In this case, you can call the above method with 3 or more values. When you call the above method, the required arguments get assigned first and if there are still any values left over they get assigned as an array to the optional argument, e.g.:
some_method(25,35,45,55) - a=25, b=35, p=[45], q=55
some_method(25,35,45) - a=25, b=35, p=[], q=45
some_method(25,35,45,55,65,75) - a=25, b=35, p=[45,55,65], q=75
Notice that the required arguments get assigned the value that corresponds to their order in the argument list, while the optional argument gets all the values that are left over that correspond to it’s order in the list.
Things can get even more involved if we introduce arguments with default values:
def some_method(a, b, c=5, *p, q) end
In this case you can still call the above method with three or more values. When you make a call, all required arguments must get a value assigned, if there are more values left over, then the arguments with default values will get a value assigned to them, after that if there is still something left over, the optional argument will get those values as an array, e.g.:
some_method(25,35,45) - a=25, b=35, c=5, p=[], q=45
some_method(25,35,45,55) - a=25, b=35, c=45, p=[], q=55
some_method(25,35,45,55,65) - a=25, b=35, c=45, p=[55], q=65
some_method(25,35,45,55,65,75) - a=25, b=35, c=45, p=[55,65], q=75
Once again all arguments get assigned the values that correspond to their order in the argument list. And the arguments with a default value will get something assigned to them (if possible) before the fully optional argument gets any values.
It’s all pretty cool and it might seem like you can do anything with argument lists in Ruby, but there are some things to look out for. The only real hard and fast rule to remember is when you’re mixing optional parameters and default value parameters in the argument list. In this case, all default value parameters must occur before the optional parameter in the list, e.g.:
def some_method(a, b=5, *p) - correct
def some_method(a, *p, b=5) - incorrect!!!
If your optional parameter occurs before your default one, it is a syntax error, which makes sense if you think about it. And obviously, it makes no sense to have two optional arguments in an argument list (i.e. two parameters with * notation).
Feel free to leave a comment if you know of any other interesting things or caveats when it comes to Ruby method arguments.
相关推荐
- Discusses naming conventions for methods in Ruby, including the use of lowercase letters and underscores for method names. 17. **Default Arguments** - Explains how to define methods with default ...
- **Comments:** The book explains the syntax for adding comments in Ruby code, which helps in documenting and explaining the purpose of the code. - **Numbers:** Ruby has built-in support for integer ...
1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to output( " Hi, my name is Jo
- **MethodName Conventions(方法命名规范)**:通常使用下划线分隔单词(如`print_name`),并且不使用括号。 - **Default Arguments(默认参数)**:为方法参数提供默认值。 - **Variable Arguments(可变参数...
Ruby方法参数实验室 学习目标 定义采用和使用参数的方法 定义一个采用和使用两个参数的方法 使用可选参数定义方法 介绍 既然我们已经看到了定义方法以向程序添加关键功能的几种方法,那么让我们尝试编写自己的方法。...
Ruby方法参数实验室 学习目标 定义采用和使用参数的方法 定义一个采用和使用两个参数的方法 使用可选参数定义方法 介绍 现在,我们已经看到了一些定义方法的方法,这些方法可以为程序添加关键功能,让我们尝试编写...
让我们看一下第一个错误: Failures: 1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to ...
- **定义格式**: `def method_name(arguments)` - **示例**: `def h; puts "Hello World"; end` - 第一行`def h`定义了一个名为`h`的方法。 - `puts "Hello World"`为方法体,用于输出文本。 - `end`表示方法...
1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to output( " Hi, my name is Jo
`method_missing`是Ruby中的一个特殊方法,它在试图调用一个未定义的方法时被触发。这为开发者提供了一个机会,可以在运行时定义或处理这些方法的调用。这种机制非常适合于创建动态方法,即那些在编译时不存在但在...
1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to output( " Hi, my name is Jo
1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to output( " Hi, my name is Jo
让我们看一下第一个错误: Failures: 1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to ...
让我们看一下第一个错误: Failures: 1) # introduction takes in an argument of a name and puts out a phrase with that name using string interpolation Failure/Error: expect{introduction( " Josh " )}.to ...
lambda_test.call(1) # 抛出 ArgumentError: wrong number of arguments (given 1, expected 2) ``` 相比之下,`lambda` 在参数数量不匹配时会抛出 `ArgumentError` 错误。这意味着 `lambda` 更加严格,要求传入的...
def some_method_with_arguments arg1, arg2 # 方法体 end # 推荐 def some_method_with_arguments(arg1, arg2) # 方法体 end ``` #### 循环控制结构 - **避免使用 `for` 循环**:大多数情况下,使用迭代器(如 ...
# args - An array of arguments (default: []) def initialize(*args) @args = args end end ``` 以上代码中,`MyLibrary::MyClass`和`initialize`方法都有相应的注释,RDoc会将这些注释转化为HTML文档中的...
context "when called with valid arguments" do # 测试逻辑 end end ``` 2. **It**: 用于定义单个测试案例,可以理解为“应该”或者“期望”的行为。 - 示例: ```ruby it "should return the correct ...
RR RR是针对Ruby的测试双重框架,具有丰富...# Stub a method to return a value when called with certain arguments stub ( object ) . foo ( 1 , 2 ) { 'bar' } stub ( MyClass ) . foo ( 1 , 2 ) { 'bar' } 嘲弄 #