LoginSignup
15
23

More than 5 years have passed since last update.

rubyのselfの意味と使い方

Posted at

Ruby の self とは?

ruby自体が持っている式らしい。(トップレベルではメソッドではないらしい)

どういうものを返してくるのか?

以下実行

sample.rb
# coding:utf-8

puts self

結果

% ruby sample.rb
main

へー。なんかわからないけど main というオブジェクト(?)を返してくる。

親はなんだろう?

先ほどのソースを修正

sample.rb
# coding:utf-8

puts self
puts self.class

結果

% ruby sample1.rb
main
Object

やっぱりオブジェクトなんだ(当たり前かw)

クラスを作成して確認する

ソース

sample2.rb
# coding:utf-8

class Sample2
    def my_self
        puts self
    end 
end

sample = Sample2.new

sample.my_self

結果

% ruby sample2.rb
#<Sample2:0x007fe4990a4a30>

クラスを返してくる。

特異メソッドで使ってみる

self付きのメソッドのことをそう呼ぶらしい。

ソース

sample3.rb
# coding:utf-8

class Sample3
    def my_self
        puts 'my_self!'
    end 

    def self.my_self_by_sample3
        puts 'self.my_self_by_sample3'
    end 
end

Sample3.my_self_by_sample3

begin
    Sample3.my_self
rescue Exception => e
    puts e
end

sample = Sample3.new

begin
    sample.my_self_by_sample3
rescue Exception => e
    puts e
end

sample.my_self

結果

% ruby sample3.rb
self.my_self_by_sample3
undefined method `my_self' for Sample3:Class
undefined method `my_self_by_sample3' for #<Sample3:0x007f6f4464aa18>
my_self!

なんとなく分かった気がする!(気だけw)

特異クラスってのもあるらしい。同じような考えなのかな?(そのうちちゃんと見てみよう)

まとめ?

普通に自分自身を返すものとして認識していいのかなぁ?
特異メソッドとして使う場合は、使っているクラス(モジュールも?)のメソッドとして動くって感じかな。
まとまりきれてないけど、ひとまずはそんな感じで認識しておこう。

参考

15
23
2

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
15
23