Method Arguments In Ruby

原文 : 

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.

时间: 2024-08-01 11:34:00

Method Arguments In Ruby的相关文章

JavaScript arguments对象

arguments 对象 JavaScript 中每个函数内都能访问一个特别变量 arguments.这个变量维护着所有传递到这个函数中的参数列表.     注意: 由于 arguments 已经被定义为函数内的一个变量.     因此通过 var 关键字定义 arguments 或者将 arguments 声明为一个形式参数,     都将导致原生的 arguments 不会被创建. arguments 变量不是一个数组(Array). 尽管在语法上它有数组相关的属性 length,但它不从

Supported method argument types Spring MVC

Supported method argument types The following are the supported method arguments: Request or response objects (Servlet API). Choose any specific request or response type, for example ServletRequest or HttpServletRequest. Session object (Servlet API):

Javascript学习笔记之函数篇(四):arguments 对象_基础知识

每一个 Javascript 函数都能在自己作用域内访问一个特殊的变量 - arguments.这个变量含有一个传递给函数的所有参数的列表. arguments 对象不是一个数组.尽管在语法上它跟数组有相同的地方,例如它拥有 length 属性.但它并不是从 Array.prototype 继承而来,实际上,它就是一个对象. 因此,我们不能直接对 arguments 使用一些数组的方法,例如 push, pop 或 slice 等. 所以为了使用这些方法,我们就需要将其转换为一个真正的数组. 转

[七]RabbitMQ-客户端源码之AMQPImpl+Method

AMQPImpl类包括AMQP接口(public class AMQImpl implements AMQP)主要囊括了AMQP协议中的通信帧的类别. 这里以Connection.Start帧做一个例子. public static class Connection { public static final int INDEX = 10; public static class Start extends Method implements com.rabbitmq.client.AMQP.C

用实际代码演示Ruby的容易被误解的6个特性_ruby专题

简介: 假设您是一名 C++ 开发人员,您需要使用 Ruby 快速执行一些原型设计.当您拿起一本 Ruby 参考书籍(比如 Pickaxe)或浏览 Ruby 网站时,会看到一些熟悉的构造,比如类声明.线程支持和异常处理.正当您认为自己了解 Ruby 的工作原理之时,您意识到了,您 Ruby 代码中的并发机制与 Boost 线程工作原理不一样,catch 和 throw 也与它们看上去的大不相同,而且其他人在其 Ruby 脚本中各处使用了名为 self 的关键词.欢迎来到 Ruby 的世界中! 如

JAVA 8:Lambdas表达式初体验

原文链接,译文链接,译者:郑旭东 Lambdas项目是即将发布(译者注:原作者写本文的时候JAVA8尚未发布)的JAVA8中重要主题,同时它应该也是众多JAVA开发者最期待的功能.还有一个非常有意思的功能同Lambda表达式一起被加入到了JAVA中,它就是Defender方法.在这篇博文中,我想去探究一些更深层次的东西--JAVA如何在运行期表达Lambda表达式的和那些字节码指令在方法调度时被调用. 虽然JAVA8尚未发布,但你仍然可以通过"下载未正式发布版本"来体验JAVA8的魅力

Ajax::prototype 源码解读_javascript技巧

AJAX之旅(1):由prototype_1.3.1进入javascript殿堂-类的初探  还是决定冠上ajax的头衔,毕竟很多人会用这个关键词搜索.虽然我认为这只是个炒作的概念,不过不得不承认ajax叫起来要方便多了.所以ajax的意思我就不详细解释了. 写这个教程的起因很简单:经过一段时间的ajax学习,有一些体会,并且越发认识到ajax技术的强大,所以决定记录下来,顺便也是对自己思路的整理.有关这个教程的后续,请关注http://www.x2design.net 前几年,javascri

PHP编码规范-php coding standard

standard|编码|规范 目录 介绍 标准化的重要性 解释 认同观点 项目的四个阶段 命名规则 合适的命名 缩写词不要全部使用大写字母 类命名 类库命名 方法命名 类属性命名 方法中参数命名 变量命名 引用变量和函数返回引用 全局变量 定义命名 / 全局常量 静态变量 函数命名 php文件扩展名 文档规则 评价注释 Comments Should Tell a Story Document Decisions 使用标头说明 Make Gotchas Explicit Interface an

Java是传值还是传引用

All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references.(摘自http://www.javagalaxy.com:8080/Interview/index.jsp?Intv=18) Java中所有方法的参数都是传值的. 然而,Java确实是通过引用来操作对