开发者

Single Ruby Value in One Line From a Collection

I have a collection of objects. There are 3 properties in each object

'id', 'name', 'is_primary'

The collection of objects will usually have anywhere from 1 to 5 objects.

What I want to do is check the collection to see if is_primary is true. If so output the name, or at least return it.

I want to do this in 1 line of code if possible. I am trying to slim up this one line for erb output in rails. Later in the page i'll output them all. I thought I had it, but if I return nil it adds extra space which shifts all the开发者_如何学编程 html oddly.

Thanks.


Hmm, this doesn't quite work if no element is_primary...I'm still thinking...

c.detect(&:is_primary).name

Ok, how about:

((a = c.detect(&:is_primary)) && a.name).to_s

As it happens, it is OK in an erb template for the <%= expression to return nil, that just results in an empty string, so for that case you can use:

(a = c.detect(&:is_primary)) && a.name

Update: Responding to the first comment, I do have a test case that I didn't post...

class A; attr_accessor :is_primary, :name, :id; end
t = [A.new, A.new, A.new, (a = A.new; a.name = 'xyz'; a.is_primary = true; a)]

puts (a = t.detect(&:is_primary)) && a.name

puts ((a = [].detect(&:is_primary)) && a.name).to_s


Complementing @DigitalRoss, you can also write:

collection.detect(&:is_primary).try(:name) || "default_if_no_element_or_name"

(well, to be honest I prefer Ick's maybe over Rails' try: c.detect(&:is_primary).maybe.name)

Side note: IMHO a flag that can only be active for a row it's not such a good idea. You may have inconsistent states with more than one being active and you'll have worry about it when updating (transactions, and so on). Try to store the PK reference somewhere else (a parent model? a state model?).

I want to do this in 1 line of code if possible. I am trying to slim up this one line for erb output in rails. Later in the page i'll output them all.

No need for one-liners (funny since I just wrote one): move the code to yous models or helpers as appropriate and keep your views pristine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜