欢迎来到山村网

Ruby中的块的知识

2019-03-02 12:43:15浏览:462 来源:山村网   
核心摘要:  这篇文章主要介绍了详解Ruby中的块的知识,包括yield语句和begin/end块等知识点,需要的朋友可以参考下  语法:  ? 12345b

  这篇文章主要介绍了详解Ruby中的块的知识,包括yield语句和begin/end块等知识点,需要的朋友可以参考下

  语法:

  ?

1 2 3 4 5 block_name{ statement1 statement2 .......... }

  在这里,将学习如何通过使用一个简单的 yield 语句调用块。还将学习使用yield语句具有参数调用块。将检查的示例代码,这两种类型的 yield 语句。

  yield 语句:

  让我们来看看在yield语句的一个例子:

  ?

1 2 3 4 5 6 7 8 9 #!/usr/bin/ruby def test puts "You are in the method" yield puts "You are again back to the method" yield end test {puts "You are in the block"}

  这将产生以下结果:

  ?

1 2 3 4 You are in the method You are in the block You are again back to the method You are in the block

  也可以通过参数与屈服声明。下面是一个例子:

  ?

1 2 3 4 5 6 7 8 #!/usr/bin/ruby def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"}

  这将产生以下结果:

  ?

1 2 3 You are in the block 5 You are in the method test You are in the block 100

  这里的 yield 语句写到后面跟着参数。甚至可以传递多个参数。在该块中放置在两条垂直线之间的变量(| |)接收的参数。因此,在上面的代码中,yield5语句将试块作为一个参数值5。

  现在看看下面的语句:

  ?

1 test {|i| puts "You are in the block #{i}"}

  在这里,在变量i中的值为5。现在遵守以下 puts 语句:

  ?

1 puts "You are in the block #{i}"

  puts 语句的输出是:

  ?

1 You are in the block 5

  如果想超过一个参数,然后yield语句就变成了:

  ?

1 yield a, b

  那么块是:

  ?

1 test {|a, b| statement}

  这些参数将用逗号隔开。

  块和方法:

  我们已经看到了如何将一个块和方法关联。通常调用块从块具有相同名称的方法,通过使用yield语句。因此,编写:

  ?

1 2 3 4 5 6 #!/usr/bin/ruby def test yield end test{ puts "Hello world"}

  这个例子是最简单的方式来实现一个块。调用块 test 使用yield语句。

  但是,如果最后一个参数的方法前面加上&,那么可以通过一个块这种方法,此块将被分配到最后一个参数。

  *和&在参数列表中&还在后面。

  ?

1 2 3 4 5 6 7 8 9 10 #!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"} This will produce following result: Hello World!

  BEGIN 和 END 块

  每一个Ruby源文件都可以声明的代码块作为文件被加载运行(BEGIN块)后,该程序已执行完毕(END块)。

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 #!/usr/bin/ruby BEGIN { # BEGIN block code puts "BEGIN code block" } END { # END block code puts "END code block" } # MAIN block code puts "MAIN code block"

  一个程序可能包括多个BEGIN和END块。 BEGIN块以遇到它们的顺序执行。 END块以相反的顺序执行。上述程序执行时,会产生以下结果:

  ?

1 2 3 BEGIN code block MAIN code block END code block
(责任编辑:豆豆)
下一篇:

介绍Ruby中的模块与混合类型的相关知识

上一篇:

Ruby中的方法概念

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com