跳到內容

程式

程式是由編譯器處理的全部原始碼。原始碼會被解析並編譯成程式的可執行版本。

程式的原始碼必須以 UTF-8 編碼。

頂層作用域

在任何其他命名空間之外定義的型別、常數、巨集和方法等功能都位於頂層作用域中。

# Defines a method in the top-level scope
def add(x, y)
  x + y
end

# Invokes the add method on the top-level scope
add(1, 2) # => 3

頂層作用域中的區域變數是檔案本地的,在方法主體內不可見。

x = 1

def add(y)
  x + y # error: undefined local variable or method 'x'
end

add(2)

私有功能也僅在目前檔案中可見。

雙冒號前綴 (::) 明確地引用頂層作用域中的命名空間、常數、方法或巨集

def baz
  puts "::baz"
end

CONST = "::CONST"

module A
  def self.baz
    puts "A.baz"
  end

  # Without prefix, resolves to the method in the local scope
  baz

  # With :: prefix, resolves to the method in the top-level scope
  ::baz

  CONST = "A::Const"

  p! CONST   # => "A::CONST"
  p! ::CONST # => "::CONST"
end

主程式碼

任何既不是方法、巨集、常數或型別定義,也不在方法或巨集主體中的表達式,都是主程式碼的一部分。主程式碼會在程式啟動時,依照原始檔案包含的順序執行。

主程式碼不需要使用特殊的進入點(例如 main 方法)。

# This is a program that prints "Hello Crystal!"
puts "Hello Crystal!"

主程式碼也可以在命名空間內

# This is a program that prints "Hello"
class Hello
  # 'self' here is the Hello class
  puts self
end