Ruby 的 BEGIN 有什么作用? [英] What does Ruby's BEGIN do?

查看:49
本文介绍了Ruby 的 BEGIN 有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BEGIN 在 Ruby 中是什么意思,它是如何调用的?例如,给定以下代码:

 输入这是第 1 句".开始 {输入这是第 2 句".}

为什么把这是第2句."先执行?

解决方案

BEGINEND 设置在执行其他任何事情之前或其他任何事情之后调用的块,就在解释器退出之前.

例如,运行这个:

END { puts 'END block' }把'foobar'BEGIN { 放置 'BEGIN 块' }

输出:

<前>开始块食物吧结束块

通常我们会为 BEGINEND 块使用更多的逻辑顺序,但这演示了它们的作用.

What does BEGIN mean in Ruby, and how is it called? For example, given this code:

puts "This is sentence 1."

BEGIN {
  puts "This is sentence 2."
}

why is puts "This is sentence 2." executed first?

解决方案

BEGIN and END set up blocks that are called before anything else gets executed, or after everything else, just before the interpreter quits.

For instance, running this:

END { puts 'END block' }

puts 'foobar'

BEGIN { puts 'BEGIN block' }

Outputs:

BEGIN block
foobar
END block

Normally we'd use a bit more logical order for the BEGIN and END blocks, but that demonstrates what they do.

这篇关于Ruby 的 BEGIN 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆