define simple method定义简单方法

关键字def用于方法定义,在其后是方法名和可选的参数名列表,参数名列表会用一对圆括号括住。构成方法主体的代码放在参数列表之后,end用于结束方法定义。

#define a method
def factorial(n)
if n<1
raise "argument must be >0"
elsif n==1
1
else
n*factorial(n-1)
end
end
puts factorial(5)

方法返回值

方法可能正常结束,也可能非正常结束。当抛出异常属于非正常结束。
如果方法正常结束,方法代码的最后一个表达式的值会作为方法调用表达式的值。

return关键字将在到达方法最后一个表达式前强行返回。如果return后面没表达式,就返回ni。

def fact2(n)
raise "bad argument " if n<1
return 1 if n==1
n*fact2(n-1)
end puts fact2(5)

对方法的最后一行也可以使用return关键字,这可以强调这个表达式用作这个方法的返回值。不过在一般的编程实践中,如非必须,会省略return。

ruby方法可以返回多个值,这必须要显式使用return语句,并把要返回的值用逗号分开:
def polar(x,y)
reutrn Maht.hypot(y,x),Math.atan2(y,x)
end

在对象上调用方法 invoking a method on a object

Methods are always invoked on an object. (This object is sometimes called the
receiver in a reference to an object-oriented paradigm in which methods are called
“messages” and are “sent to” receiver objects.) Within the body of a method, the keyword
self refers to the object on which the method was invoked. If we don’t specify
an object when invoking a method, then the method is implicitly invoked on self.

  You’ll learn how to define methods for classes of objects in Chapter 7. Notice, however,
that you’ve already seen examples of invoking methods on objects, in code like this:
first = text.index(pattern)

  Like most object-oriented languages, Ruby uses . to separate the object from the method
to be invoked on it. This code passes the value of the variable pattern to the method
named index of the object stored in the variable text, and stores the return value in the
variable first.

定义单键方法define a singleton method

  目前为止,我们定义的方法都是全局方法。如果把前面的那些def语句放在一个class语句中,这些方法就成为了该类的实例方法,他们被定义在这个类的所有实例对象上。

不过,也可以使用def语句为一个特定的对象定义方法,只需简单地在def关键字后加上一个求值结果为对象的表达式,在这个表达式 之后需要一个句点符号和要定义的方法名。这样定义的方法称为单键方法,因为他只在单个对象上可用:

o="message"
def o.printme
puts self
end
o.printme #输出message

如果在fixnum定义单键方法,会报错:<main>': can't define singleton method "printme" for Fixnum (TypeError)

取消方法定义undef method

Methods are defined with the def statement and may be undefined with the undef
statement:

def sum(x,y)
x+y
end
puts sum(1,2)
undef sum

In this code, the def statement defines a global method, and undef undefines it. undef
also works within classes (which are the subject of Chapter 7) to undefine the instance
methods of the class. Interestingly, undef can be used to undefine inherited methods,
without affecting the definition of the method in the class from which it is inherited.
Suppose class A defines a method m, and class B is a subclass of A and therefore inherits
m. (Subclasses and inheritance are also explained in Chapter 7.) If you don’t want to

allow instances of class B to be able to invoke m, you can use undef m within the body
of the subclass.
undef is not a commonly used statement. In practice, it is much more common to
redefine a method with a new def statement than it is to undefine or delete the method.
Note that the undef statement must be followed by a single identifier that specifies the
method name. It cannot be used to undefine a singleton method in the way that def
can be used to define such a method.
Within a class or module, you can also use undef_method (a private method of Module)
to undefine methods. Pass a symbol representing the name of the method to be
undefined.

ruby Methods, Procs, Lambdas, and Closures的更多相关文章

  1. [翻译]理解Ruby中的blocks,Procs和lambda

    原文出处:Understanding Ruby Blocks, Procs and Lambdas blocks,Procs和lambda(在编程领域被称为闭包)是Ruby中很强大的特性,也是最容易引 ...

  2. 《ruby编程语言》笔记 1

    赋值: ruby支持并行赋值,即允许在赋值表达式中出现多余一个值和多于一个的变量: x,y=1,2a,b=b,ax,y,z=[1,2,3] (python同样可以正常上面的语句). Methods i ...

  3. Day06 - Ruby三种存取限制:Public,Protected,Private

    前情提要: 在第五天的最后,我们提到了一句话“相同的class的实体也无法使用别人的singleton method”. 在今天,我们把焦点放在Ruby的method,继续了解存取限制:) Ruby经 ...

  4. Ruby学习笔记2 : 一个简单的Ruby网站,搭建ruby环境

    Ruby on Rails website 的基础是 请求-返回 循环. 首先是浏览器请求服务器, 第二步,Second, in our Rails application, the route ta ...

  5. 你应该学会使用的5个ruby方法

    今天看到了这篇文章--Five Ruby Methods You Should Be Using,感觉收获颇丰,先简单翻译一下先. 作者写这篇文章的契机是在Exercism上看到了很多ruby代码可以 ...

  6. A Complete List of .NET Open Source Developer Projects

    http://scottge.net/2015/07/08/a-complete-list-of-net-open-source-developer-projects/?utm_source=tuic ...

  7. Kotlin 语言高级安卓开发入门

    过去一年,使用 Kotlin 来为安卓开发的人越来越多.即使那些现在还没有使用这个语言的开发者,也会对这个语言的精髓产生共鸣,它给现在 Java 开发增加了简单并且强大的范式.Jake Wharton ...

  8. 使用 PHP 7 给 Web 应用加速

    PHP 20周年了!?? PHP 首发通告,1995年6月8日 发布于 COMP.INFOSYSTEMS.WWW.AUTHORING.CGI 主题:正式宣布:个人主页工具(Personal Home ...

  9. WEBrick/Rack Puppet Master

    Puppet's Services: The WEBrick Puppet Master Puppet master is the application that compiles configur ...

随机推荐

  1. Orchard 学习-手动安装Orchard

    通过Orchard zip 文件手动配置网站 这篇文章将引导你如果通过Zip文件来安装Orchard. 我们会使用三种不同的方法来承载Orchard: IIS. WebMatrix and IIS E ...

  2. sql 游标循环遍历

    写存储过程的时候碰到一个需要对数据进行遍历循环操作的问题,最后通过游标解决了,感觉很适用. declare @level varchar() declare @uid varchar() declar ...

  3. c语言学习之基础知识点介绍(十六):文件操作

    一.文件的分类 1.文本文件:打开之后能看得懂的文件 2.二进制文件:打开之后看不懂,类似乱码之类的文件(视频,音频打开之后,能看.听,是应为电脑中装有播放器,播放器中含有解码器). 二.操作文件的步 ...

  4. NewtonSoft.json 序列化和反序列化实例

    在百度 API Store 找个旅游的 API 来当成本次 Demo 的例子 接口地址:http://apis.baidu.com/apistore/attractions/spot AIPKEY: ...

  5. C/C++中memset函数

    本文学习参考http://baike.baidu.com/link?url=ZmSyY8ciB_nJt9KM-W2fiEFJrC2mugFsLqRdY2b4pLe8rD_jRXyN7_pj0GBBD2 ...

  6. IIS配置及防黑

    安装IIS.部署网站(发布或者拷贝都可以).修改连接字符串,compilation设为false,删掉cs代码 上传文件夹不给执行权限: 在iis管理器中找到上传文件夹,选择属性--执行权限,设置为“ ...

  7. ubuntu fcitx 安装 使用

    系统内置的ibus的86五笔,感觉有些老不太好用, 所以安装试用了一下fcitx下的五笔,记录一下安装方法 ,各种搜索... 我的ubuntn版本: #48-Ubuntu SMP Fri Aug 24 ...

  8. jQuery siblings()用法与实例。

    jQuery 的遍历方法siblings() $("给定元素").siblings(".selected") 其作用是筛选给定的同胞同类元素(不包括给定元素本身 ...

  9. 网站开发常用jQuery插件总结(15)上传插件blueimp

    在介绍这个插件之前,先吐槽一下.这个插件功能很强大.带有的功能有:上传(单个文件或批量文件),自动上传或点击按钮上传,上传前缩略图显示,判断文件格式,上传前的文件操作,上传时进度条显示等功能.如果你用 ...

  10. js在php 中出现 unterminated string literal 解决方法

    出现这个问题就是空格造成的(可清空格符,换行符等) 示例代码如下: php 下报错 <?php echo "<a href=javascript:if(window.confir ...