#!/usr/bin/env ruby =begin ********************************************************************** This is a comment block, something you write for the benefit of human readers (including yourself). The interpreter ignores it. There is no need for a '#' at the start of every line. ********************************************************************** =end
组织你的代码
Ruby读到什么就处理什么.没有编译处理;如果有什么还没读到,就被简单地认为未定义.
# this results in an "undefined method" error: print successor(3),"\n" def successor(x) x + 1 end
# Conversion of fahrenheit to celsius, broken # down into two steps. def f_to_c(f) scale(f - 32.0) # This is a forward reference, but it's okay. end def scale(x) x * 5.0 / 9.0 end printf "%.1f is a comfortable temperature.\n", f_to_c(72.3)
#!/usr/bin/env ruby def main # Express the top level logic here... end # ... put support code here, organized as you see fit ... main # ... and start execution here.
Ruby也提供了将复杂程序分割为可读,可重用,逻辑相关的大块的工具.我们已看到用 include 来访问模块.你将发现 load 和 require 也很有用.load的作用类似于文件的复制加粘贴(和C的#include处理器指令相似).require更复杂,仅在需要时才加载,而且最多加载一次.load和require还有其它一些区别;在语言手册,FAQ中可找到更多信息.