0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

class_attribute

Posted at

クラスの属性値を変更することができる(自分自身、自分のサブクラスができる)

class_attributeメソッドは、1つ以上の継承可能なクラスの属性を宣言します。そのクラス属性は、その下のどの階層でも上書き可能です。

1つ以上の継承可能なクラスの属性を宣言

irb(main):001:1* class A
irb(main):002:1*   class_attribute(:some_attribute, default: 1)
irb(main):003:0> end
=> [:some_attribute]
irb(main):004:0> A.some_attribute
=> 1
...
irb(main):006:0> class B < A; end
=> nil
irb(main):007:0> class C < A; end
=> nil
irb(main):008:0> A.some_attribute
=> 1
irb(main):009:0> B.some_attribute
=> 1
irb(main):010:0> C.some_attribute
=> 1
irb(main):011:0> C.some_attribute = 2
=> 2
irb(main):012:0> C.some_attribute
=> 2
irb(main):013:0> B.some_attribute
=> 1

クラスでオーバーライドできる

これらの属性はインスタンスのレベルでアクセスまたはオーバーライドできます。

irb(main):014:0> a = A.new
=> #<A:0x000000010ceac7e0>
irb(main):015:0> a.some_attribute
=> 1
irb(main):016:0> b = B.new
=> #<B:0x000000010c5d30b0>
irb(main):017:0> b.some_attribute
=> 1
irb(main):018:0> c = C.new
=> #<C:0x000000010cdb4a18>
irb(main):019:0> c.some_attribute
=> 2

インスタンスのクラス属性値の書き込みを不可能

irb(main):001:1* class A
irb(main):002:1*   class_attribute(:some_attribute, default: 1, instance_writer: false)
irb(main):003:0> end
=> [:some_attribute]
irb(main):004:0> A.some_attribute = 3
=> 3
irb(main):005:0> a = A.new
=> #<A:0x0000000114603230>
irb(main):006:0> a.some_attribute
=> 3
irb(main):007:0> a.some_attribute = 4
(irb):7:in `<main>': undefined method `some_attribute=' for #<A:0x0000000114603230> (NoMethodError)

a.some_attribute = 4
 ^^^^^^^^^^^^^^^^^
Did you mean?  some_attribute

インスタンスのクラスの属性値の読み込みを不可能

irb(main):001:1* class A
irb(main):002:1*   class_attribute(:some_attribute, instance_reader: false)
irb(main):003:0> end
=> [:some_attribute]
irb(main):004:0> a = A.new
=> #<A:0x00000001087184b0>
irb(main):005:0> a.some_attribute
(irb):5:in `<main>': undefined method `some_attribute' for #<A:0x00000001087184b0> (NoMethodError)

a.some_attribute
 ^^^^^^^^^^^^^^^
Did you mean?  some_attribute=

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?