如何在Ruby中的一行中定义方法?

Rya*_*wis 86 ruby

def greet; puts "hello"; end在Ruby中在一行上定义方法的唯一方法吗?

hor*_*guy 94

如果使用括号,则可以避免使用分号:

def hello() :hello end
Run Code Online (Sandbox Code Playgroud)


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)

来自bbatsov/ruby​​-style-guide.


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)

  • 在Ruby 2+中似乎没有被弃用 (4认同)

Vic*_*gin 9

其他方式:

define_method(:greet) { puts 'hello' }
Run Code Online (Sandbox Code Playgroud)

如果您不想在定义方法时输入方法的新范围,则可以使用此方法.

  • `define_method`已在Ruby 1.9中"私有化" (3认同)

Jos*_*h D 6

另一种方式:

def greet() return 'Hello' end
Run Code Online (Sandbox Code Playgroud)

  • 在Ruby中,方法的返回值是最后一个语句返回的值.你不需要这里的`return`,因为它不是一个保护条款. (12认同)

Dan*_*Dan 6

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代码库的整个方法定义