Ruby中的BEGIN或END保留字是什么? [英] What are the reserved words BEGIN or END used for in Ruby?

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

问题描述

这是一个很难找到的单词,因为在大多数情况下,它们在搜索过程中并不敏感. 在文档之外,我能找到的最好的方法是在IRB中进行测试.

This is a very hard to find word because in most cases they are not sensitive during a search. The best I could find outside of documentation is a test in IRB.

 BEGIN{puts x = 10}
 10

推荐答案

所有关键字 BEGINEND记录为 Object 的公共实例方法(即使您看不到它们是从Object.public_instance_methods返回的)

As all keywords BEGIN and END are documented as public instance methods of Object (even though you won't see them returned from Object.public_instance_methods)

BEGIN (BEGIN )通过代码块指定要在程序的顺序执行开始之前无条件执行的代码. 有时用于模拟对方法的前向引用.

BEGIN Designates, via code block, code to be executed unconditionally before sequential execution of the program begins. Sometimes used to simulate forward references to methods.

puts times_3(gets.to_i)

BEGIN {
  def times_3(n)
    n * 3
  end
}

END (通过代码块)指定要在程序终止之前执行的代码.

END Designates, via code block, code to be executed just prior to program termination.

END { 
  puts "Bye!" 
}

对Ruby进行编程的实用程序员指南

BEGIN和END块

每个Ruby源文件都可以声明要作为 文件正在加载(BEGIN块),并且在程序执行完之后 完成执行(END块).

Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).

BEGIN {   
  begin code 
}

END {
  end code 
}

一个程序可能包含多个BEGIN和END块. BEGIN块是 按照遇到的顺序执行. END块在以下位置执行 倒序.

A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.

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

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