| 著作一覧 |
こんなのが簡単に書けるメソッドはあるかな?
[1, 2, 3, 4, 5].inject([]) do |a, x}
if x % 2 == 0
a << x + 1
end
a
end
Enumerable#selectとは違って元の要素ではないものを入れる。Enumerable#collectとは違って不要な要素は削除する。
具体的にはこういう処理をしたい。
require 'pathname'
def child_dirs(dir)
Pathname.new(dir).children.inject([]) do |a, x|
if x.directory? && x.basename.to_s[0..0] != '.'
a << x.basename.to_s
end
a
end
end
これを
def child_dirs(dir)
Pathname.new(dir).children.filter do |x|
(x.directory? && x.basename.to_s[0..0]) ? x.basename.to_s : nil
end
end
と書けるのがEnumerable#filter。でも、nilが要素として入れられないってのはまずいか……
module Enumerable
def filter(&p)
inject([]) do |a, x|
n = p.call(x)
if n
a << n
end
a
end
end
end
ジェズイットを見習え |
selectしてからcollectでよいのでは?<br>[1,2,3,4,5].select{|x| x % 2 == 0}.collect{|x| x+1}
切れ目が欲しいな。
↑携帯から書いたんで意味不明になっている。セレクト&コレクトしたいんじゃなくて、フィルタしたいという意味なので、本当は切れ目があってはならないんだけど、つい実装に気を取られたので逆に書き方になっている。なんていうか、2+2+2+2は、2*4とは違うということが言いたかっただけで、もちろん結果的にはその通りだと思います。