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

Enumerable モジュールを include して、eachによる繰り返し処理を用いたメソッドを利用する

Posted at
class FriendList
  include Enumerable

  def initialize(*friends)
    @friends = friends
  end

  def each
    for v in @friends
      yield v
    end
  end
end

Enumerable を include して each メソッドを定義すると、以下のようにmapやfindメソッドを使用できるようになる。

friends = FriendList.new('Alice', 'Bob', 'Charlie')

friends.map { |v| v.upcase }
=> ["ALICE", "BOB", "CHARLIE"]

friends.find { |v| /b/ === v }
=> "Bob"
1
3
1

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