在Ruby中使用yield和return

时间:2012-05-04 14:44:25

标签: ruby block

任何人都可以帮我弄清楚Ruby中yield和return的用法。我是一名Ruby初学者,非常感谢这些简单的例子。

提前谢谢!

3 个答案:

答案 0 :(得分:29)

return语句的工作方式与它在其他类似编程语言上的工作方式相同,只是从它使用的方法返回。 您可以跳过要返回的调用,因为ruby中的所有方法始终返回最后一个语句。所以你可能会找到这样的方法:

def method
  "hey there"
end

这实际上与做类似的事情相同:

def method
  return "hey there"
end
另一方面,{p> yield会将作为参数给出的块作为方法。所以你可以有这样的方法:

def method 
  puts "do somthing..."
  yield
end

然后像这样使用它:

method do
   puts "doing something"
end

结果是,将在屏幕上打印以下两行:

"do somthing..."
"doing something"

希望能稍微清理一下。有关块的更多信息,您可以查看this link

答案 1 :(得分:6)

yield用于调用与该方法关联的块。你可以通过在方法及其参数之后放置块(基本上只是花括号中的代码)来实现这一点,如下所示:

[1, 2, 3].each {|elem| puts elem}

return退出当前方法,并使用其“参数”作为返回值,如下所示:

def hello
  return :hello if some_test
  puts "If it some_test returns false, then this message will be printed."
end

但请注意, 在任何方法中都不能使用return关键字;如果遇到没有返回,Ruby将返回评估的最后一个语句。因此这两者是公平的:

def explicit_return
  # ...
  return true
end

def implicit_return
  # ...
  true
end

以下是yield的示例:

# A simple iterator that operates on an array
def each_in(ary)
  i = 0
  until i >= ary.size
    # Calls the block associated with this method and sends the arguments as block parameters.
    # Automatically raises LocalJumpError if there is no block, so to make it safe, you can use block_given?
    yield(ary[i])
    i += 1
  end
end

# Reverses an array
result = []     # This block is "tied" to the method
                #                            | | |
                #                            v v v
each_in([:duck, :duck, :duck, :GOOSE]) {|elem| result.insert(0, elem)}
result # => [:GOOSE, :duck, :duck, :duck]

return的示例,我将用它来实现一个方法,以查看数字是否为happy

class Numeric
  # Not the real meat of the program
  def sum_of_squares
    (to_s.split("").collect {|s| s.to_i ** 2}).inject(0) {|sum, i| sum + i}
  end

  def happy?(cache=[])
    # If the number reaches 1, then it is happy.
    return true if self == 1
    # Can't be happy because we're starting to loop
    return false if cache.include?(self)
    # Ask the next number if it's happy, with self added to the list of seen numbers
    # You don't actually need the return (it works without it); I just add it for symmetry
    return sum_of_squares.happy?(cache << self)
  end
end

24.happy? # => false
19.happy? # => true
2.happy?  # => false
1.happy?  # => true
# ... and so on ...

希望这有帮助! :)

答案 2 :(得分:0)

def cool
  return yield
end

p cool {"yes!"}

yield关键字指示Ruby执行块中的代码。在此示例中,块返回字符串"yes!"。在cool()方法中使用了显式返回语句,但这也可能是隐含的。

相关问题