拼音 - 打印答案"if own answer (itself)"



Ruby问题:

我可以缩短以下代码吗:

total = Paper.where(available: true).count
puts total if total > 0

我想象这样的东西,但我不知道是否可能:

puts Paper.where(available: true).count if itself > 0

有没有办法用一句话把这个想法写下来?

if (total = Paper.where(available: true).count) > 0 then puts total end

更新:使用实例变量你可以做

puts @total if (@total = Paper.where(available: true).count) > 0

你所拥有的一切都是完美的。为了好玩,您可以在一行代码中使用object# tap:

Paper.where(available: true).count.tap { |total| puts total if total > 0 }

我能想到的最接近的东西是这样的:

total = Paper.where(available: true).count; puts total if total > 0 

它和你原来的完全一样,只是它用分号分隔行而不是新行。它往往可读性较差,所以我通常会避免这样做。

作为旁注,虽然我理解你想做什么,但老实说,将你的代码从2行减少到1行并不是什么大事。坦率地说,这样很好。

最新更新