ruby Methods, Procs, Lambdas, and Closures

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,布布扣,bubuko.com

时间: 2024-08-06 11:51:11

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

Functional PHP 5.3 Part I - What are Anonymous Functions and Closures?

One of the most exciting features of PHP 5.3 is the first-class support for anonymous functions. You may have heard them referred to as closures or lambdas as well. There's a lot of meaning behind these terms so let's straighten it all out. What is t

《ruby编程语言》笔记 1

赋值: ruby支持并行赋值,即允许在赋值表达式中出现多余一个值和多于一个的变量: x,y=1,2a,b=b,ax,y,z=[1,2,3] (python同样可以正常上面的语句). Methods in Ruby are allowed to return more than one value, and parallel assignmentis helpful in conjunction with such methods. For example:# Define a method to

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=tuicool NET Implementations .NET Core – Core .NET Framework C# Native – Compiles C# to native. Cosmos – C# Open Source Managed Operating System, an operat

Kotlin 语言高级安卓开发入门

过去一年,使用 Kotlin 来为安卓开发的人越来越多.即使那些现在还没有使用这个语言的开发者,也会对这个语言的精髓产生共鸣,它给现在 Java 开发增加了简单并且强大的范式.Jake Wharton 在他的 Øredev 的讨论中,提到了 Kotlin 是如何通过提升安卓开发的语言特性和设计模式来解决这些严重的问题,通过这些方法你可以清除那些无用的 API 还有无效代码.充分利用扩展特性来解决你的开发中的模板性代码的问题! 为什么要推广这个语言? 好吧,大伙.欢迎来到这里.我们今天的主题是使用

Part 99 Lambda expression in c#

class Program { static void Main(string[] args) { List<Person> persons = new List<Person>() { new Person{ID=101,Name="lin1"}, new Person{ID=102,Name="lin2"}, new Person{ID=103,Name="lin3"} }; Person person = perso

Ruby_day[1]控制流2

summary: 1: puts "s in #{user_input}" 和puts 's in #{user_input}'不同,前者#{user_input}会输出user_input的值,后者只是输出鸳原样,s in #{user_input} 1 print "Thtring, pleathe!: " 2 user_input = gets.chomp 3 user_input.downcase! 4 5 if user_input.include? &q

C# for Beginner Part 98 to 100

Part 98   Anonymous methods in c# What is an anonymous method? Anonymous method is a method without a name. Introduced in C# 2.0,they provide us a way of creating delegate instances without having to write a separate method. class Program { static vo

Java 终于有 Lambda 表达式啦~Java 8 语言变化&mdash;&mdash;Lambda 表达式和接口类更改【转载】

原文地址 en cn 下载 Demo Java? 8 包含一些重要的新的语言功能,为您提供了构建程序的更简单方式.Lambda 表达式 为内联代码块定义一种新语法,其灵活性与匿名内部类一样,但样板文件要少得多.接口更改使得接口可以添加到现有接口中,同时又不会破坏与现有代码的兼容性.本文将了解这些更改是如何协同工作的. Java 8 的最大变化在于添加了对 lambda 表达式 的支持.Lambda 表达式是可按引用传递的代码块.类似于一些其他编程语言中的闭包:它们是实现某项功能的代码,可接受一个

浅析Ruby中的methods,private_methods和instance_methods

首先,methods,private_methods是Object类的实例方法;instance_methods是Module类的实例方法. 我们先来看看这样安排的原因: 我们知道一个Ruby对象所能调用的方法包含在其祖先链中(包含这个对象的单例类).这里所说的Ruby对象可以分为2类,一类是普通对象,像"abc",2,obj=Object.new这种对象,它们所属的类分别是String,Fixnum,Object,我们称这种对象为普通对象:还有一类对象是类(类本身也是一种对象),像S