少しずつ Ruby の勉強を進めています。今回は Enumerable。
Ruby の Enumerable モジュールを include したクラスは、C# の LINQ に似た構文でオブジェクトを検索できます。
Array クラスが Enumerable モジュールを include しているみたいなので、このクラスで試してみました。
#人クラス class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end people = Array.new people << Person.new("ルフィ", 17) people << Person.new("ゾロ", 19) people << Person.new("ナミ", 18) people << Person.new("ウソップ", 17) people << Person.new("サンジ", 19) #LINQ みたいに絞り込む results = people.select{ |p| p.age > 17 }. sort_by { |p| p.age }. collect { |p| p.name } puts results
ナミ ゾロ サンジ
また、each メソッドが定義してあって、Enumerable モジュールを include しているクラスなら、同じ操作が可能になります。
#人クラス class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end #人々クラス class People include Enumerable def initialize @array = Array.new end def <<(person) @array << person end def each @array.each do |person| yield person end end end people = People.new people << Person.new("ルフィ", 17) people << Person.new("ゾロ", 19) people << Person.new("ナミ", 18) people << Person.new("ウソップ", 17) people << Person.new("サンジ", 18) #LINQ みたいに絞り込む results = people.select{ |p| p.age > 17 }. sort_by{ |p| p.age }. collect { |p| p.name } puts results
ナミ ゾロ サンジ
Enumerable 便利。
p | が何度も登場したり、行末のピリオドが気になるけど。 |