Nobody
2015/12/05 10:19:10 投稿
1

【Refactor Me】もっと短く書けそう...

短くなっているかは不明ですが、managerに選定をselectを用いて処理を明瞭にしています。

Before

managers = []
employees.each do |e|
  managers << e if e.manager?
end

After

class Employee
	attr_reader :name

	def initialize(name, manager = false)
		@name = name
		@manager = manager
	end
	def manager?
		@manager
	end
end

employees = [
	Employee.new("hoge"),
	Employee.new("huga", true),
	Employee.new("hugo"),
	Employee.new("hiyo", true),
	Employee.new("piyo", true),
]

managers = employees.select do |e|
	e.manager?
end

managers.each do |m|
	p m.name
end

みんなのコメント