LoginSignup
64
47

More than 1 year has passed since last update.

rubyにおける::(ダブルコロン、コロンコロン)についてのメモ

Last updated at Posted at 2018-06-16

rubyにおける::(ダブルコロン、コロンコロン)について、調べました。

1番目、rubyでは、メソッドや定数を呼び出す場合に::ダブルコロンが使われます。

class Colon
  def method
    puts "Colon"
  end
end

c = Colon.new
c::method
# Colon

引用元)https://qiita.com/ktarow/items/772014a4f0d48905f3ef

2番目、Ruby では名前空間の(トップレベルからのパス)絶対パスで指定する場合に::ダブルコロンが使われます。

class Foo; end 

module MyNameSpace
class Foo; end

def foo1 
::Foo.new # 一番上のFoo
end

def foo2
Foo.new # MyNameSpace::Foo
end
end

引用元)https://teratail.com/questions/3382

3番目、スコープ演算子としての::(ダブルコロン)
C++でも、::(ダブルコロン)はスコープ演算子として使っている。

config/initializers/constants.rb

module Constants
  AgeStart = 0
  AgeEnd   = 99
end
app/modles/customer.rb
class Customer < ActiveRecord::Base
  age_start = Constants::AgeStart #=> 0
  age_end   = Constants::AgeEnd   #=> 99
  validates :age, :inclusion => { :in => age_start..age_end }
end

引用元)https://qiita.com/nashirox/items/0c885edf7d78fd5a83f1

class Hoge
  FUGA = "piyo"
end

p Hoge::FUGA #=> "piyo"

引用元)https://qiita.com/mnuma/items/22338399a86064c61f24

4番目、ではこの、ActiveRecord::Baseの二重コロンはどれに該当するのか?

class User < ActiveRecord::Base
  
end

参考記事
https://teratail.com/questions/20825
http://www.atmarkit.co.jp/ait/articles/1104/12/news135.html

参考記事では、BaseはActiveRecordの親クラスである、と教えてくれています。
4番のクラスの継承で::ダブルコロンが使われている場合は、何番の使われ方なのだろうか?

なお、deviseでも4番のように使われます。

class RegistrationsController < Devise::RegistrationsController

end

理解が深まったら、追記します。

64
47
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
47