8

How to write this more succinctly?

 3 years ago
source link: https://www.codesd.com/item/how-to-write-this-more-succinctly.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to write this more succinctly?

advertisements

Is there a construction in RoR that would allow me to write this:

@budget_project_amounts.detect {|attributes| attributes['id'] == 659 }.attributes['amount'] if !@budget_project_amounts.detect {|attributes| attributes['id'] == 659 }.nil?

more succinctly? Without the use of a variable...

Edit: This part

@budget_project_amounts.detect {|attributes| attributes['id'] == 659 }

is irrelevant. It could be anything. I sometimes have a situation like this one, where I first need to check if something is nil, before being able to continue to get a value under it (in case it's not nil and I'm looking for a way to do this without having to repeat the first part completely. I hope this makes sense.


You could try with short circuits, for instance (to mention your example):

(bp = @budget_project_amount.find { |b| b['id'] == 12 }) && bp['amount']

The result of the expression is either nil or the amount you are searching for. Less than this I cannot think of anything.

It's called short-circuit because if the first expression evaluates to false, than the second one is not evaluated, avoiding calling the method on a nil object.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK