views:

73

answers:

1

Hey guys,

I am trying to get a collection of objects based on a conditions. Now normally in C# I would do something like this

employeesCollection.Where(emp => emp.Name == "john");

how can I do something similar in Ruby on Rails (I am trying to map a collection of objects to a select but I only want to map certain objects that match a condition.

My current ruby on rails code looks like this

<%= select( 'page', 'id', @post.pages.map {|page| [page.title, page.id]}) %>

I want to add a condition to an attribute of page

Can anyone help?

+5  A: 

You can just throw a select block in there before map:

>> [1,2,3,4,5].select { |x| x.odd? }.map{ |x| x*x }
=> [1, 9, 25]

A synonym for select is find_all.

As you probably guessed, select in Ruby is approximately equivalent to LINQ's Where. Select takes a block, and each element in your Enumerable is passed to that block; when the block returns true (non-false, non-nil), then that element is selected.

The antonym for select is reject. reject is preferred when your select is negative: that is to say,

ary.select {|x| x != 'foo'}

is less preferable than

ary.reject {|x| x == 'foo'}
Mark Rushakoff
You're a god among men, great answer. Thanks!
Jimmy