Ser*_*eev 68
请给出全新的答案:
一般来说,避免使用单行方法.虽然它们在野外有点受欢迎,但它们的定义语法有一些特殊之处,使得它们的使用不受欢迎.无论如何 - 单行方法中应该只有 一个表达式.
# bad
def too_much; something; something_else; end
# okish - notice that the first ; is required
def no_braces_method; body end
# okish - notice that the second ; is optional
def no_braces_method; body; end
# okish - valid syntax, but no ; make it kind of hard to read
def some_method() body end
# good
def some_method
body
end
Run Code Online (Sandbox Code Playgroud)
该规则的一个例外是空体方法.
# good
def no_op; end
Run Code Online (Sandbox Code Playgroud)
edg*_*ner 39
def add a,b; a+b end
Run Code Online (Sandbox Code Playgroud)
分号是Ruby的内联语句终止符
或者您可以使用该define_method方法.(编辑:这个在ruby 1.9中被弃用)
define_method(:add) {|a,b| a+b }
Run Code Online (Sandbox Code Playgroud)
其他方式:
define_method(:greet) { puts 'hello' }
Run Code Online (Sandbox Code Playgroud)
如果您不想在定义方法时输入方法的新范围,则可以使用此方法.
另一种方式:
def greet() return 'Hello' end
Run Code Online (Sandbox Code Playgroud)
Ruby 3.0.0为只有一个语句的方法添加了“无限”定义:
def greet = puts("hello")
Run Code Online (Sandbox Code Playgroud)
请注意,单语句限制意味着这不能写为:
# NOT ALLOWED
def greet = puts "hello"
SyntaxError: unexpected string literal, expecting `do' or '{' or '('
def greet = puts "hello"
^
Run Code Online (Sandbox Code Playgroud)
这种变化似乎是为了鼓励使用单行方法,或者适应它们很常见但很难阅读的现实—— “这种简单的方法定义[估计]占了 24%ruby/ruby代码库的整个方法定义。
| 归档时间: |
|
| 查看次数: |
37668 次 |
| 最近记录: |