2012-06-15 42 views
35

可能重複:
What does :: mean in Ruby?。 VS ::(點與雙冒號)調用方法

我從Poignant Guide to Ruby和一些代碼示例學習Ruby,

File::open('idea-' + idea_name + '.txt', 'w') do |f| 
    f << idea 
end 

在上面的代碼中,我對面,似乎是用於同一目的的雙冒號和點的用途來雙冒號正被用於訪問File類的open方法。不過,我後來整個代碼中的點爲同一目的傳來:

require 'wordlist' 
# Print each idea out with the words fixed 
Dir['idea-*.txt'].each do |file_name| 
    idea = File.read(file_name) 
    code_words.each do |real, code| 
    idea.gsub!(code, real) 
    end 
puts idea 
end 

這個時候,一個點被用來訪問File類的read方法。是什麼區別:

File.read() 

File::open() 
+0

參見[什麼是Ruby的雙冒號(::)所有關於(http://stackoverflow.com/questions/3009477/what-is-rubys-雙冒號 - 全約)。 – sczizzo

+26

我真的不認爲這是重複的。在這個問題或其答案中沒有任何地方使用關於所討論的單例方法的'::'。 –

+8

我同意。在我打開這個之前,我看到了另一個問題。但是,我的問題的答案沒有明確給出。另一個問題討論僅使用::運算符。也許它暗示了以微妙的方式使用點運算符,但是當你對某些東西不熟悉時,你需要以非常不同的形式回答。就像我說的,我對ruby很陌生。 – flyingarmadillo

回答

21

這是scope resolution operator

維基百科的一個例子:

module Example 
    Version = 1.0 

    class << self # We are accessing the module's singleton class 
    def hello(who = "world") 
     "Hello #{who}" 
    end 
    end 
end #/Example 

Example::hello # => "Hello world" 
Example.hello "hacker" # => "Hello hacker" 

Example::Version # => 1.0 
Example.Version # NoMethodError 

# This illustrates the difference between the message (.) operator and the scope 
# operator in Ruby (::). 
# We can use both ::hello and .hello, because hello is a part of Example's scope 
# and because Example responds to the message hello. 
# 
# We can't do the same with ::Version and .Version, because Version is within the 
# scope of Example, but Example can't respond to the message Version, since there 
# is no method to respond with. 
+18

這並不回答這個問題:「File.read()'和'File :: open()'?之間有什麼區別?爲什麼都可以用來調用一個方法?我們什麼時候會選擇一個呢? – antinome

+26

::和之間沒有區別。當在功能中調用類(靜態)方法時。但是你可以使用::來訪問常量和其他名稱空間的東西,爲此你不能使用點。我個人一直使用dot,但我的同事使用::來調用靜態方法。當你調用Foo :: Bar :: open(而不是Foo :: Bar.open)這樣的命名空間的東西時,它可能在美學上更加美觀,但它在兩種方式下都是相同的。性能也一樣。附:這裏是很好的討論這個話題:https://www.ruby-forum.com/topic/107527 –

+8

@DaliborFilus評論應該是接受的答案,真的... –