连续收集/选择/拒绝/每个时的代码折叠
我在 ruby 中经常使用数组和哈希,最终得到一些如下所示的代码:(
sum = two_dimensional_array.select{|i|
i.collect{|j|
j.to_i
}.sum > 5
}.collect{|i|
i.collect{|j|
j ** 2
}.average
}.sum
让我们假设上面的代码示例现在有意义......)
问题是,即使 TextMate(我的编辑器) choice)很容易地选择简单的 {...}
或 do...end
块,它无法弄清楚(这是可以理解的,因为即使我也不能找到折叠上面的“正确”方法)上面的块开始和结束折叠它们的位置。
您将如何折叠上面的代码示例?
PS:考虑到它可以有2层折叠,我只关心外面的连续折叠(带有i的块)
I play around with arrays and hashes quite a lot in ruby and end up with some code that looks like this:
sum = two_dimensional_array.select{|i|
i.collect{|j|
j.to_i
}.sum > 5
}.collect{|i|
i.collect{|j|
j ** 2
}.average
}.sum
(Let's all pretend that the above code sample makes sense now...)
The problem is that even though TextMate (my editor of choice) picks up simple {...}
or do...end
blocks quite easily, it can't figure out (which is understandable since even I can't find a "correct" way to fold the above) where the above blocks start and end to fold them.
How would you fold the above code sample?
PS: considering that it could have 2 levels of folding, I only care about the outer consecutive ones (the blocks with the i)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
老实说,一些令人费解的事情可能会让 TextMate 感到困惑,就像其他必须维护它的人一样,这也包括将来的您。
每当您看到某些内容汇总为单个值时,这就是使用 Enumerable#inject 的好例子。
在你的例子中奇怪的是你使用 select 返回完整的数组,据称使用 to_i 转换,但实际上 Enumerable#select 没有做这样的事情,而是拒绝函数返回 nil 的任何数组。我猜这不符合你的价值观。
另外,根据 .average 方法的实现方式,您可能希望使用 0.0 而不是 0 为注入调用提供种子以使用浮点值。
To be honest, something that convoluted is probably confusing TextMate as much as anyone else who has to maintain it, and that includes you in the future.
Whenever you see something that rolls up into a single value, it's a good case for using Enumerable#inject.
What's odd in your example is you're using select to return the full array, allegedly converted using to_i, but in fact Enumerable#select does no such thing, and instead rejects any for which the function returns nil. I'm presuming that's none of your values.
Also depending on how your .average method is implemented, you may want to seed the inject call with 0.0 instead of 0 to use a floating-point value.