Ruby 中方法名称的限制是什么? [英] What are the restrictions for method names in Ruby?
问题描述
例如,我在下面的代码片段中找到了方法名称 bundler?
,但不知道 ?
字符是专用关键字还是只是其中的一部分方法名称.
For example, I found the method name bundler?
in the following snippet, and don't know whether the ?
character is a specialized keyword or just part of the method name.
# This is a predicate useful for the doc:guides task of applications.
def bundler?
# Note that rake sets the cwd to the one that contains the Rakefile
# being executed.
File.exists?('Gemfile')
end
推荐答案
Ruby 中的方法名称可以包含大小写字母、数字、下划线 _
和标点符号 !
、?
、=
.
Method names in Ruby may contain upper-case and lower-case letters, numbers, underscores _
and the punctation signs !
, ?
, =
.
方法名不能以数字开头,字符!
、?
和=
只能出现在末尾.
A method name can't begin with a number, and the characters !
, ?
and =
can only appear at the end.
可以在方法名称中使用非 ASCII 字符,但这会导致非常混乱的情况,不应该是常见的做法.
Non-ASCII characters can be used in a method name, but this can lead to very confusing situations and should not be common practice.
以小写字符开头的方法名称虽然不是强制性的,但这是一种很好的做法,因为以大写字母开头的名称在 Ruby 中是常量.仍然可以为方法使用常量名称,但您将无法在没有括号的情况下调用它,因为 interpeter 会将名称作为常量进行查找:
It's good practice, while not mandatory, to start the method name with a lower-case character, because names that start with capital letters are constants in Ruby. It's still possible to use a constant name for a method, but you won't be able to invoke it without parentheses, because the interpeter will look-up for the name as a constant:
def Capital
nil
end
Capital # NameError: uninitialized constant Capital
Capital() # => nil
在定义方法名称时,一些非常广泛且一致使用的约定是:
Some very widely and consistently used conventions when defining method names are:
方法名称全部小写,下划线
_
作为名称中单词的分隔符(例如Math::sqrt
、Array#each_index
, ...).
Method names are full down-case, with underscores
_
as separators for words into the name (e.g.Math::sqrt
,Array#each_index
, ...).
谓词有一个问号 ?
作为最后一个字符(例如 Array#empty?
、Hash#has_key?
, ...).虽然谓词通常返回布尔值,但情况并非总是如此:如果谓词评估为假,这些方法只需要返回 nil
或 false
,否则返回任何其他值(例如File::size?
返回 nil
如果文件不存在,文件的大小为 Integer
否则).
Predicates have a question mark ?
as last character (e.g. Array#empty?
, Hash#has_key?
, ...). While predicates usually return boolean values, this is not always the case: these methods just need to return nil
or false
if the predicate evaluates to false, any other value otherwise (e.g. File::size?
returns nil
if the file does not exist, the size of the file as an Integer
otherwise).
修改被调用对象状态的方法,或具有异常行为的方法的最后一个字符是感叹号!
;这种方法有时被称为 mutators 因为它们通常是其他方法的破坏性或就地版本(例如 Array#sort!
、Array#slice!
, ...).
Methods that modify the state of the object on which they are invoked, or that have an unusual behavior have an exclamation mark !
as last character; this methods are sometimes called mutators because they usually are destructive or in-place versions of other methods (e.g. Array#sort!
, Array#slice!
, ...).
Setters 有一个等号 =
作为最后一个字符(例如 Array#[]=
, ...);Ruby interpeter 为调用 setter 方法提供了语法糖:
Setters have an equal sign =
as last character (e.g. Array#[]=
, ...); the Ruby interpeter offers syntactic sugar for invokation of setter methods:
a = [4, 5, 6]
a[0] = 3 # Shorthand for a.[]=(0, 3)
Ruby 还允许使用运算符符号作为方法名称来定义运算符:
Ruby also allows to define operators using the operator symbol as the method name:
╔═══════════════════════════╦═════════════════════════════════════════════╦═══════╗
║ Operators (by precedence) ║ Operations ║ Arity ║
╠═══════════════════════════╬═════════════════════════════════════════════╬═══════╣
║ ! ~ + ║ Boolean NOT, bitwise complement, unary plus ║ 1 ║
║ ║ (define with method name +@, Ruby 1.9+) ║ ║
║ ║ ║ ║
║ ** ║ Exponentiation ║ 2 ║
║ ║ ║ ║
║ - ║ Unary minus (define with method name -@) ║ 1 ║
║ ║ ║ ║
║ * / % ║ Multiplication, division, modulo ║ 2 ║
║ ║ ║ ║
║ + - ║ Addition, subtraction ║ 2 ║
║ ║ ║ ║
║ << >> ║ Bitwise shift ║ 2 ║
║ ║ ║ ║
║ & ║ Bitwise AND ║ 2 ║
║ ║ ║ ║
║ | ^ ║ Bitwise OR, Bitwise XOR ║ 2 ║
║ ║ ║ ║
║ < <= => > ║ Ordering ║ 2 ║
║ ║ ║ ║
║ == === != =~ !~ <=> ║ Equality, pattern matching, comparison ║ 2 ║
╚═══════════════════════════╩═════════════════════════════════════════════╩═══════╝
一元运算符方法不传递参数;二元运算符方法传递一个参数,并对它和 self
进行操作.
Unary operator methods are passed no arguments; binary operator methods are passed an argument, and operate on it and on self
.
严格遵守操作符的数量很重要;虽然可以定义具有不同数量的运算符方法(例如,带有两个参数的 +
方法),但 Ruby 不允许您使用运算符语法调用该方法(但是它可以使用点语法).
It's important to adhere strictly to the arity of the operators; while it is possible to define operator methods with a different arity (e.g. a +
method that takes two arguments), Ruby would not allow you to call the method with operator syntax (it would however work with dot syntax).
尽可能遵循运算符的原始语义是一种很好的做法:对于了解运算符原始含义的人来说,它应该是直观的.
It's good practice to adhere to the original semantics of the operators as much as possible: it should be intuitive to someone who knows the original meaning of the operator how it works with user defined classes.
该语言还为通常用于访问数组和哈希值的特殊非运算符、[]
方法提供了语法糖.[]
方法可以定义为任意数量.
The language also offers syntactic sugar for the special, non-operator ,[]
method that is normally used for accessing array and hash values. The []
method can be defined with arbitrary arity.
对于表中的每个二元运算符,除了排序、相等、比较和模式匹配,Ruby 还提供了缩写赋值的简写(例如 x += y
扩展为 x = x +y
);您不能将它们定义为方法,但您可以通过定义它们所基于的运算符来改变它们的行为.
For every binary operator in the table, except ordering, equality, comparison and pattern matching, Ruby also offers shorthand for abbreviated assignment (e.g. x += y
expands to x = x + y
); you can't define them as methods, but you can alter their behavior defining the operators on which they're based.
这些字符都不能在普通方法名称中使用(例如,do&print
或 start-up
不是有效的方法名称).
None of these characters can be used inside normal method names (e.g. do&print
or start-up
are not valid method names).
这篇关于Ruby 中方法名称的限制是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!