self と self.class の違い

  • self.class は自身のクラスを返す。
  • self は自身のクラスまたはインスタンスを返す。
class Hoge
  def moge
    puts self.class.methods
  end

  def noge
    puts self.methods
  end
end

h = Hoge.new
h.moge
puts "-----"
h.noge

出力結果は下記となる。

new
allocate
superclass
<=>
module_exec
class_exec
<=
>=
==
===
include?
included_modules
ancestors
name
public_instance_methods
instance_methods
private_instance_methods
protected_instance_methods
const_get
constants
const_defined?
const_set
class_variables
class_variable_get
remove_class_variable
class_variable_defined?
class_variable_set
private_constant
public_constant
singleton_class?
deprecate_constant
freeze
inspect
module_eval
const_missing
prepend
method_defined?
class_eval
public_method_defined?
private_method_defined?
<
public_class_method
>
protected_method_defined?
private_class_method
to_s
autoload
autoload?
instance_method
public_instance_method
include
instance_of?
public_send
instance_variable_get
instance_variable_set
instance_variable_defined?
remove_instance_variable
private_methods
kind_of?
instance_variables
tap
public_method
singleton_method
is_a?
extend
define_singleton_method
method
to_enum
enum_for
=~
!~
eql?
respond_to?
display
object_id
send
nil?
hash
class
singleton_class
clone
dup
itself
taint
tainted?
untaint
untrust
trust
untrusted?
methods
protected_methods
frozen?
public_methods
singleton_methods
!
!=
__send__
equal?
instance_eval
instance_exec
__id__
-----
moge
noge
instance_of?
public_send
instance_variable_get
instance_variable_set
instance_variable_defined?
remove_instance_variable
private_methods
kind_of?
instance_variables
tap
public_method
singleton_method
is_a?
extend
define_singleton_method
method
to_enum
enum_for
<=>
===
=~
!~
eql?
respond_to?
freeze
inspect
display
object_id
send
to_s
nil?
hash
class
singleton_class
clone
dup
itself
taint
tainted?
untaint
untrust
trust
untrusted?
methods
protected_methods
frozen?
public_methods
singleton_methods
!
==
!=
__send__
equal?
instance_eval
instance_exec
__id__
  • self.methodsインスタンスのメソッド一覧を返すので、インスタンスメソッドであるhogemogeが含まれている。
  • self.class.methods はクラスHogeのメソッド一覧を返すので、インスタンスメソッドであるhogemogeが含まれていない。