在Ruby中使用yield和return

nxh*_*oaf 14 ruby block

任何人都可以帮我弄清楚Ruby中yield和return的使用.我是一个Ruby初学者,所以很简单的例子非常受欢迎.

先感谢您!

Del*_*man 31

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

def method
  "hey there"
end
Run Code Online (Sandbox Code Playgroud)

这实际上与做类似的事情是一样的:

def method
  return "hey there"
end
Run Code Online (Sandbox Code Playgroud)

yield另一方面,excecutes给出作为参数传递给该方法的块.所以你可以有这样的方法:

def method 
  puts "do somthing..."
  yield
end
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

method do
   puts "doing something"
end
Run Code Online (Sandbox Code Playgroud)

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

"do somthing..."
"doing something"
Run Code Online (Sandbox Code Playgroud)

希望能稍微清理一下.有关块的更多信息,您可以查看此链接.

  • 这是一个很好的 [链接](http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes) (2认同)

Jwo*_*sty 6

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

[1, 2, 3].each {|elem| puts elem}
Run Code Online (Sandbox Code Playgroud)

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

def hello
  return :hello if some_test
  puts "If it some_test returns false, then this message will be printed."
end
Run Code Online (Sandbox Code Playgroud)

但请注意,你不具备使用任何方法返回的关键字; 如果遇到没有返回,Ruby将返回评估的最后一个语句.因此这两者是等价的:

def explicit_return
  # ...
  return true
end

def implicit_return
  # ...
  true
end
Run Code Online (Sandbox Code Playgroud)

这是一个例子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]
Run Code Online (Sandbox Code Playgroud)

还有一个例子return,我将用它来实现一个方法来查看数字是否满意:

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 ...
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!:)