2
3

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で[ ](カギ括弧)メソッドを定義する

Posted at

Array型やHash型などのインスタンス変数の要素を [添字] の記法で取得するためには[]メソッドを定義します。

以下のようにメソッド名を[]で定義すると、添字に指定した値が引数として渡されます。

def [](引数名)
end

使用例

class ConfigModel
  attr_reader :config

  def initialize
    @config = {host: "127.0.0.1", port: 3000}
  end

  def [](key)
    @config[key]
  end
end

config = ConfigModel.new
puts config[:host]
puts config[:port]

出力結果

127.0.0.1
3000
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?