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

时间:2010-11-29 07:26:49

标签: ruby

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

6 个答案:

答案 0 :(得分:90)

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

def hello() :hello end

答案 1 :(得分:65)

请给出全新的答案:

一般避免使用单行方法。虽然它们在野外有点受欢迎,但它们的定义语法有一些特殊之处,使得它们的使用不受欢迎。无论如何 - 应该有 单行方法中的表达式不超过一个

# 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

该规则的一个例外是空体方法。

# good
def no_op; end

来自bbatsov/ruby-style-guide

答案 2 :(得分:39)

def add a,b; a+b end

分号是Ruby

的内联语句终止符

或者您可以使用define_method方法。 (编辑:这个在ruby 1.9中被弃用)

define_method(:add) {|a,b| a+b }

答案 3 :(得分:9)

另一种方式:

define_method(:greet) { puts 'hello' }

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

答案 4 :(得分:6)

另一种方式:

def greet() return 'Hello' end

答案 5 :(得分:5)

Ruby 3.0.0 adds "endless" definitions 用于只有一个语句的方法:

def greet = puts("hello")

请注意,单一语句的限制意味着这不能写成:

# NOT ALLOWED
def greet = puts "hello"

SyntaxError: unexpected string literal, expecting `do' or '{' or '('
def greet = puts "hello"
                 ^

似乎此更改旨在encourage the use of one-line methods或适应它们非常常见但难以阅读的现实-"this kind of simple method definition [is estimated to] account for 24% of the entire method definitions" of the ruby/ruby code base