RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Enumerable#filter

Inspired by every and Haskell’s filter command I came up with a very quick and dirty Ruby version which works like this:

test = [1,5,3,2,1,6,4,3,2,1] test.filter('> 3') # => [5, 6, 4] (1..10).filter('%2==0') # => [2, 4, 6, 8, 10] 'hello'.filter(">'a'") # => "hello"

Comments

test.filter('> 3; `rm -Rf /`')

eval(string) for the lose.

See Enumerable#select

@Jordi: The whole point of this was to have a nicer syntax for Enumberable#select (filter actually uses select).

@sandal: Yes, that was why I was asking for feedback, I knew I was overlooking something really obvious here. Thanks!

Update: Thanks to sandal’s feedback I rewrote Enumberable#filter so it doesn’t use ‘eval’. It’s a bit less flexible now and I also like the syntax less, but at least it doesn’t eat puppies for breakfast.

test = [1,5,3,2,1,6,4,3,2,1] test.filter(‘>=’, 3) # => [5, 3, 6, 4, 3]

quiz = [0,0,0,1,0,0,1,1,0,1] attempted = quiz.filter(‘==’, 1) # => [1, 1, 1, 1]

As the disclaimer said, maybe it was a bad idea to begin with…

I think you’ll find this useful:

http://weblog.raganwald.com/2007/10/stringtoproc.html

I just hacked up a FilterableEnumerable that allows this (clearer) syntax:

a = (1..10).to_a a.filter >= 5 # => [5, 6, 7, 8, 9, 10] a.filter > 5 # => [6, 7, 8, 9, 10] a.filter < 5 # => [1, 2, 3, 4] a.filter <= 5 # => [1, 2, 3, 4, 5] a.filter == 5 # => [5]

I added to jqr’s implementation to let you call any method on the filter, and have it be called inside the select, ie a.filter.zero?. Also added some test/unit to help verify it.

http://gist.github.com/89491

Doing array.filter != foo is still problematic. I took a page from rspec though, and added filter_not. This lets you do:

array.filter_not == 5 array.filter_not.valid?

http://gist.github.com/90627

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in