10
8

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.

Crystal - Rubyと異なるアクセサの命名 #ruby #crystal

Posted at

CrystalとRubyではアクセサ定義時のメソッド名(マクロ名)が異なります。

:gem: Rubyの場合

下記のメソッドはModuleで定義されています。
Module - るりま

-- 読み込み 書き込み メソッド名
o o attr_accessor
o x attr_reader
x o attr_writer

Crystalの場合

下記のマクロはObjectで定義されています。
Object - Crystal Docs

-- 読み込み 書き込み メソッド名
o o property
o x getter
x o setter

Crystal命名議論Issueより

On the other hand, I never really liked attr_accessor, attr_reader and attr_writer.
In every other language they are called property, getter and setter.

Issue全体を見てみたい方は以下より

Issue651(method naming conventions ) - Crystal - GitHub

サンプル

:gem: Rubyプログラム

require 'pp'
class Person
  attr_accessor :name
  attr_reader :age
  attr_writer :hello
  def initialize(name, age)
    @name, @age = name, age
  end

  def say_hello
    puts @hello
  end
end

tanaka = Person.new('tanaka', 22)
pp tanaka                      # => #<Person:0x0000060031cdc8 @age=22, @name="tanaka">
pp tanaka.name                 # =>"tanaka"
pp tanaka.name = 'tanaka-kai'  # =>"tanaka-kai"
pp tanaka.age                  # =>22
# pp tanaka.age = 33 => Error
pp tanaka.hello = "hello"      # =>"hello"
tanaka.say_hello               # =>hello

Crystalプログラム

class Person
  property :name
  getter :age
  setter :hello
  def initialize(@name, @age)
    # crystalでは引数にインスタンス変数を指定すると、
    # そのまま値がインスタンス変数に設定される
  end

  def say_hello
    puts @hello
  end
end

tanaka = Person.new("tanaka", 22)
pp tanaka                      # => tanaka = #<Person:0x949ff90 @name="tanaka", @age=22, @hello=nil>
pp tanaka.name                 # =>tanaka.name = "tanaka"
pp tanaka.name = "tanaka-kai"  # =>tanaka.name = "tanaka-kai" = "tanaka-kai"
pp tanaka.age                  # =>tanaka.age = 22
# pp tanaka.age = 33 => Error
pp tanaka.hello = "hello"      # =>tanaka.hello = "hello" = "hello"
tanaka.say_hello               # =>hello

どっち?

どっちがお好みですか?

外部資料

10
8
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
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?