1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby : Objectクラスの基本

Last updated at Posted at 2018-04-09

Objectクラスは全てのクラスのスーパークラス。また、ObjectクラスはKernelモジュールをインクルードしているため、全てのオブジェクトでKernelモジュールのメソッドを使用できる。

###オブジェクトID

> a = "bagu"
> a.object_id
 => 2115678909

> a.__id__
 => 2115678909

Rubyでは全てがオブジェクトであるため、同じリテラルであっても基本的にはオブジェクトIDは異なる。
しかし、TrueClass, FalseClass, NilClass, Symbol, Fixumクラスのインスタンスは、同じリテラルであれば、同じIDとなる。

> :bagu.class
 => String
> "bagu".object_id
 => 3212398798
> "bagu".object_id
 => 3212397653

> :bagu.class
 => Symbol
> :bagu.object_id
 => 3498473892
> :bagu.object_id
 => 3498473892                         注.インスタンスの前に : をつけないとエラーになる。
                     

###equal?メソッド / eql?メソッド

equal?メソッドはオブジェクトIDを比較、 eql?メソッドはハッシュのキーを比較する。

> a = "bagu"
 => "bagu"
> a.hash
 => 574895934
> a.object_id
 => 345678903

> b = "bagu"
 => "bagu"
> b.hash
 => 574895934          # ハッシュのキーは同じ
> b.object_id
 => 345673491                    # IDは異なる

> a.eql?(b)
 => true
> a.equal?(b)
 => false

###オブジェクトのメソッド

irb(main):007:0> a.methods
=> [:include?, :%, :unicode_normalize, :*, :+, :to_c, :unicode_normalize!, :unicode_normalized?, :count, :partition, :unpack, :encode, :encode!, :next, :casecmp, :insert, :bytesize, :match, :succ!, :next!, :upto, :index, :rindex, :replace, :clear, :chr, :+@, :-@, :setbyte, :getbyte, :<=>, :<<, :scrub, :scrub!, :byteslice, :==, :===, :dump, :=~, :downcase, :[], :[]=, :upcase, :downcase!, :capitalize, :swapcase, :upcase!, :oct, :empty?, :eql?, :hex, :chars, :split, :capitalize!, :swapcase!, :concat, :codepoints, :reverse, :lines, :bytes, :prepend, :scan, :ord, :reverse!, :center, :sub, :freeze, :inspect, :intern, :end_with?, :gsub, :chop, :crypt, :gsub!, :start_with?, :rstrip, :sub!, :ljust, :length, :size, :strip!, :succ, :rstrip!, :chomp, :strip, :rjust, :lstrip!, :tr!, :chomp!, :squeeze, :lstrip, :tr_s!, :to_str, :to_sym, :chop!, :each_byte, :each_char, :each_codepoint, :to_s, :to_i, :tr_s, :delete, :encoding, :force_encoding, :sum, :delete!, :squeeze!, :tr, :to_f, :valid_encoding?, :slice, :slice!, :rpartition, :each_line, :b, :ascii_only?, :to_r, :hash, :<, :>, :<=, :>=, :between?, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :define_singleton_method, :is_a?, :public_method, :extend, :singleton_method, :to_enum, :enum_for, :!~, :respond_to?, :display, :object_id, :send, :method, :nil?, :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__]
irb(main):008:0> a.private_methods
=> [:initialize, :initialize_copy, :DelegateClass, :default_src_encoding, :irb_binding, :sprintf, :format, :Integer, :Float, :String, :Array, :Hash, :catch, :throw, :loop, :block_given?, :Rational, :trace_var, :untrace_var, :at_exit, :Complex, :set_trace_func, :select, :caller, :caller_locations, :test, :fork, :`, :exit, :sleep, :respond_to_missing?, :load, :syscall, :printf, :open, :putc, :print, :readline, :puts, :p, :exit!, :system, :readlines, :gets, :rand, :srand, :proc, :lambda, :gem_original_require, :initialize_clone, :initialize_dup, :exec, :trap, :spawn, :abort, :require, :require_relative, :autoload, :autoload?, :gem, :binding, :local_variables, :warn, :raise, :fail, :global_variables, :__method__, :__callee__, :__dir__, :eval, :iterator?, :method_missing, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined]
irb(main):009:0> a.protected_methods
=> []
irb(main):010:0> a.public_methods
=> [:include?, :%, :unicode_normalize, :*, :+, :to_c, :unicode_normalize!, :unicode_normalized?, :count, :partition, :unpack, :encode, :encode!, :next, :casecmp, :insert, :bytesize, :match, :succ!, :next!, :upto, :index, :rindex, :replace, :clear, :chr, :+@, :-@, :setbyte, :getbyte, :<=>, :<<, :scrub, :scrub!, :byteslice, :==, :===, :dump, :=~, :downcase, :[], :[]=, :upcase, :downcase!, :capitalize, :swapcase, :upcase!, :oct, :empty?, :eql?, :hex, :chars, :split, :capitalize!, :swapcase!, :concat, :codepoints, :reverse, :lines, :bytes, :prepend, :scan, :ord, :reverse!, :center, :sub, :freeze, :inspect, :intern, :end_with?, :gsub, :chop, :crypt, :gsub!, :start_with?, :rstrip, :sub!, :ljust, :length, :size, :strip!, :succ, :rstrip!, :chomp, :strip, :rjust, :lstrip!, :tr!, :chomp!, :squeeze, :lstrip, :tr_s!, :to_str, :to_sym, :chop!, :each_byte, :each_char, :each_codepoint, :to_s, :to_i, :tr_s, :delete, :encoding, :force_encoding, :sum, :delete!, :squeeze!, :tr, :to_f, :valid_encoding?, :slice, :slice!, :rpartition, :each_line, :b, :ascii_only?, :to_r, :hash, :<, :>, :<=, :>=, :between?, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :define_singleton_method, :is_a?, :public_method, :extend, :singleton_method, :to_enum, :enum_for, :!~, :respond_to?, :display, :object_id, :send, :method, :nil?, :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__]
irb(main):011:0> a.singleton_methods
=> []
irb(main):012:0> 

###オブジェクトの複製 :cloneメソッド

class Dog
   attr_accessor :name
   def initialize(name)
      @name = name
   end
end

original = Cat.new("Maro")
copied = original.clone
puts copied.equal?(original)
puts copied.neme

=>false
=>Maro

参照:Rubyリファレンス, https://ref.xaio.jp/ruby/classes/object/clone

###cloneとdup

cloneメソッドはオブジェクトの凍結状態、汚染状態、信頼状態をコピーする。dupメソッドは汚染状態と信頼状態をコピーするが、凍結状態はコピーしない。

cloneメソッドはオブジェクトの特異メソッドもコピーする。dupメソッドはコピーしない。

###インスタンス変数へのアクセス


> class Goo
>   def initialize
>       @hoge = 1
>   end
> end
 => nil
> f = Goo.new
 => #<Goo:0x2020948390 @hoge=1>
> f.instance_variables             #インスタンス変数の一覧
 => ["@hoge"]
> f.instance_variable_get(:@hoge)    #インスタンス変数の取得
 => 1
>f.instance_variable_set(:@hoge, 2)   #インスタンス変数の設定
 => 2
>f.instance_variable_get(:@hoge)
 => 2

     

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?