コードを圧縮するRubyの黒魔術
まあ、行数的な意味で。正直、黒魔術でもなんでもないんですけど。
Rubyでプログラム書いてると、結構コードが短くなるよなーとおもうので、
ちょっとインスパイアされて書いてみる。
コレクションを使う
よくあるカタチを短くできる。
Before
managers = [] employees.each do |e| managers << e if e.manager? end
After
managers = employees.select{|e| e.manager?}
Before
friends = [] people.each do |person| friends << person if person == "Aon" friends << person if person == "Bon" friends << person if person == "Con" friends << person if person == "Don" friends << person if person == "Eon" end
After
friends = people.select do |person| %w[Aon Bon Con Don Eon].include? person end
こんなかんじか。
やっぱり書いてて楽しいなー
最近はリファクタリングの勉強中。
高いけど、結構楽しい。オススメ。
- 作者: Jay Fields,Shane Harvie,Martin Fowler,Kent Beck,長尾高弘
- 出版社/メーカー: アスキー・メディアワークス
- 発売日: 2010/02/27
- メディア: 大型本
- 購入: 8人 クリック: 312回
- この商品を含むブログ (37件) を見る